Монетопедия
encyclopediamonetwiki
https://encyclopediamonet.miraheze.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0
MediaWiki 1.41.0
first-letter
Медиа
Служебная
Обсуждение
Участник
Обсуждение участника
Монетопедия
Обсуждение Монетопедии
Файл
Обсуждение файла
MediaWiki
Обсуждение MediaWiki
Шаблон
Обсуждение шаблона
Справка
Обсуждение справки
Категория
Обсуждение категории
Модуль
Обсуждение модуля
Заглавная страница
0
1
1
2024-04-28T13:21:24Z
MediaWiki default
1
Добро пожаловать в Miraheze!
wikitext
text/x-wiki
__NOTOC__
== Добро пожаловать в {{SITENAME}}! ==
Эта главная страница была создана автоматически и, похоже, ещё не заменена.
=== Для бюрократа(-ов) этой вики ===
Здравствуйте и добро пожаловать на вашу новую вики! Благодарим Вас за выбор Miraheze в качестве хостинга, и мы надеемся, что вы будете пользоваться нашими услугами.
Вы можете сразу же начать работать над вашем вики-сайтов, как только пожелаете.
Нужна помощь? Нет проблем! Мы поможем вам с вашей вики по мере необходимости. Для того, чтобы начать, мы добавили несколько ссылок о работе с MediaWiki:
* [[mw:Special:MyLanguage/Help:Contents|Обсуждение руководства MediaWiki (например, навигация, редактирование, удаление страниц, блокирование пользователей)]]
* [[meta:Special:MyLanguage/FAQ|ЧЗВ по Miraheze]]
* [[meta:Special:MyLanguage/Request features|Запрос изменений настроек вашей вики.]] (Изменения расширений, оформления и логотипа/фавикона должны выполняться через [[Special:ManageWiki]] в вашей вики, см. [[meta:Special:MyLanguage/ManageWiki|ManageWiki]] для получения дополнительной информации.)
==== Но, Miraheze, я всё ещё не понимаю X! ====
Что ж, это не проблема. Даже если что-то не описано в документации/ЧЗВ, мы всё равно будем рады помочь вам. Вы можете найти нас здесь:
* [[meta:Special:MyLanguage/Help center|На нашем собственном Miraheze вики]]
* На [[phorge:|Phorge]]
* На нашем [https://miraheze.org/discord Discord-сервере]
* На IRC в #miraheze в irc.libera.chat (irc.libera.chat ([irc://irc.libera.chat/%23miraheze direct link]; [https://web.libera.chat/?channel=#miraheze вебчат]))
=== Для посетителя этой вики ===
Здравствуйте, заглавная страница по умолчанию ещё не была заменена бюрократом(-ами) этой вики. Возможно, администрация этого сайта разрабатывает эту страницу, поэтому мы рекомендуем вам зайти чуть позже.
da708791005da529f6c1fffe139a9b3660d023e2
MediaWiki:Common.css
8
2
2
2024-04-29T01:07:20Z
Genka Barboskin
2
Новая страница: «/* Размещённый здесь CSS будет применяться ко всем темам оформления */ @import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap'); /* Прозрачный фон */ .page__main { background-color: rgba(var(--theme-page-background-color--rgb), 0.86); } /* Шрифт в заголовке */ .MirahezePage .wds-community-header__sitename, #content .wds-ta...»
css
text/css
/* Размещённый здесь CSS будет применяться ко всем темам оформления */
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');
/* Прозрачный фон */
.page__main {
background-color: rgba(var(--theme-page-background-color--rgb), 0.86);
}
/* Шрифт в заголовке */
.MirahezePage .wds-community-header__sitename, #content .wds-tabs,
.resizable-container .miraheze-community-header__community-name-wrapper,
.miraheze-community-header .miraheze-community-header__community-name,
.resizable-container .miraheze-community-header__community-name-wrapper a {
font-family: 'PT Serif';
text-shadow: #000000 1px 0 10px;
}
/** Genka Barboskin **/
a[href$="/Genka_Barboskin"],
a[href$=":Genka_Barboskin"] {
color: #008000;
font-family: 'PT Serif';
text-shadow: #008000 1px 0 10px;
}
8ae329c3fe3ca84ac0610006da52517457c440f9
3
2
2024-04-29T01:20:43Z
Genka Barboskin
2
css
text/css
/* Размещённый здесь CSS будет применяться ко всем темам оформления */
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');
/* Прозрачный фон */
.page__main {
background-color: rgba(var(--theme-page-background-color--rgb), 0.86);
}
/** Genka Barboskin **/
a[href$="/Genka_Barboskin"],
a[href$=":Genka_Barboskin"] {
color: #008000;
font-family: 'PT Serif';
text-shadow: #008000 1px 0 10px;
}
9e4115b7b28db9e8b456df595416b62c739f6fc3
17
3
2024-04-29T03:16:18Z
Genka Barboskin
2
css
text/css
/* Размещённый здесь CSS будет применяться ко всем темам оформления */
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');
/* Прозрачный фон */
.page__main {
background-color: rgba(var(--theme-page-background-color--rgb), 0.86);
}
/** Genka Barboskin **/
a[href$="/Genka_Barboskin"],
a[href$=":Genka_Barboskin"] {
color: #008000;
font-family: 'PT Serif';
text-shadow: #008000 1px 0 10px;
}
/* Сообщения */
/* Амбокс, мбокс, тмбокс и другие */
.mbox-text,
.mbox-text { /* The message body cell(s) */
border: none;
/* @noflip */
padding: 0.25em 0.9em; /* 0.9em left/right */
width: 100%; /* Make all mboxes the same width regardless of text length */
}
.mbox-image { /* The left image cell */
border: none;
/* @noflip */
padding: 2px 0 2px 0.9em; /* 0.9em left, 0px right */
text-align: center;
}
.mbox-imageright { /* The right image cell */
border: none;
/* @noflip */
padding: 2px 0.9em 2px 0; /* 0px left, 0.9em right */
text-align: center;
}
.mbox-empty-cell { /* An empty narrow cell */
border: none;
padding: 0px;
width: 1px;
}
.mbox-text .mbox-multiply {
display: none;
}
/* Image message box styles */
.imbox {
margin: 4px 10%;
border-collapse: collapse;
border: 3px solid #1e90ff; /* Default "notice" blue */
background: #fbfbfb;
}
.imbox .mbox-text .imbox { /* For imboxes inside imbox-text cells. */
margin: 0 -0.5em; /* 0.9 - 0.5 = 0.4em left/right. */
display: block; /* Fix for webkit to force 100% width. */
}
.mbox-inside .imbox { /* For imboxes inside other templates. */
margin: 4px;
}
.imbox-notice {
border: 2px solid #1e90ff; /* Blue */
}
.imbox-speedy {
border: 2px solid #b22222; /* Red */
background: #fee; /* Pink */
}
.imbox-delete {
border: 2px solid #b22222; /* Red */
}
.imbox-content {
border: 2px solid #f28500; /* Orange */
}
.imbox-style {
border: 2px solid #f4c430; /* Yellow */
}
.imbox-move {
border: 2px solid #9932cc; /* Purple */
}
.imbox-protection {
border: 2px solid #bba; /* Gray-gold */
}
.imbox-license {
border: 2px solid #88a; /* Dark gray */
background: #f7f8ff; /* Light gray */
}
.imbox-featured {
border: 2px solid #cba135; /* Brown-gold */
}
/* Category message box styles */
.cmbox {
margin: 3px 10%;
border-collapse: collapse;
border: 1px solid #aaa;
background: #dfe8ff; /* Default "notice" blue */
}
.cmbox-notice {
background: #d8e8ff; /* Blue */
}
.cmbox-speedy {
margin-top: 4px;
margin-bottom: 4px;
border: 4px solid #b22222; /* Red */
background: #ffdbdb; /* Pink */
}
.cmbox-delete {
background: #ffdbdb; /* Red */
}
.cmbox-content {
background: #ffe7ce; /* Orange */
}
.cmbox-style {
background: #fff9db; /* Yellow */
}
.cmbox-move {
background: #e4d8ff; /* Purple */
}
.cmbox-protection {
background: #efefe1; /* Gray-gold */
}
/* Other pages message box styles */
.ombox {
margin: 4px 10%;
border-collapse: collapse;
border: 1px solid #a2a9b1; /* Default "notice" gray */
background: #f8f9fa;
}
.ombox-notice {
border: 1px solid #a2a9b1; /* Gray */
}
.ombox-speedy {
border: 2px solid #b22222; /* Red */
background: #fee; /* Pink */
}
.ombox-delete {
border: 2px solid #b22222; /* Red */
}
.ombox-content {
border: 1px solid #f28500; /* Orange */
}
.ombox-style {
border: 1px solid #f4c430; /* Yellow */
}
.ombox-move {
border: 1px solid #9932cc; /* Purple */
}
.ombox-protection {
border: 2px solid #bba; /* Gray-gold */
}
/* Talk page message box styles */
.tmbox {
margin: 4px 10%;
border-collapse: collapse;
border: 1px solid #c0c090; /* Default "notice" gray-brown */
background: #f8eaba;
}
.mediawiki .mbox-inside .tmbox { /* For tmboxes inside other templates. The "mediawiki" class ensures that */
margin: 2px 0; /* this declaration overrides other styles (including mbox-small above) */
width: 100%; /* For Safari and Opera */
}
.mbox-inside .tmbox.mbox-small { /* "small" tmboxes should not be small when */
line-height: 1.5em; /* also "nested", so reset styles that are */
font-size: 100%; /* set in "mbox-small" above. */
}
.tmbox-speedy {
border: 2px solid #b22222; /* Red */
background: #fee; /* Pink */
}
.tmbox-delete {
border: 2px solid #b22222; /* Red */
}
.tmbox-content {
border: 2px solid #f28500; /* Orange */
}
.tmbox-style {
border: 2px solid #f4c430; /* Yellow */
}
.tmbox-move {
border: 2px solid #9932cc; /* Purple */
}
.tmbox-protection,
.tmbox-notice {
border: 1px solid #c0c090; /* Gray-brown */
}
/* {ambox} */
.ambox {
margin: 0 10%; /* 10% = Will not overlap with other elements */
border: 1px solid #a2a9b1;
/* @noflip */
border-left: 10px solid #36c; /* Default "notice" blue */
background: #fbfbfb;
}
.theme-fandomdesktop-dark .ambox{
background: #1B2932;
}
.ambox + .ambox { /* Single border between stacked boxes. */
margin-top: -1px;
}
.ambox .mbox-text,
.ambox .mbox-text { /* The message body cell(s) */
padding: 0 0.5em; /* 0.5em left/right */
}
.ambox .mbox-image { /* The left image cell */
/* @noflip */
padding: 2px 0 2px 0.5em; /* 0.5em left, 0px right */
}
.ambox .mbox-imageright { /* The right image cell */
/* @noflip */
padding: 2px 0.5em 2px 0; /* 0px left, 0.5em right */
}
.navbox + .ambox { /* for ambox 1em before navbox */
margin-top: 1em;
}
.ambox-notice {
/* @noflip */
border-left: 10px solid #36c; /* Blue */
}
.ambox-speedy {
/* @noflip */
border-left: 10px solid #b22222; /* Red */
background: #fee7e6; /* Pink */
}
.ambox-delete,
.ambox-serious {
/* @noflip */
border-left: 10px solid #b22222; /* Red */
}
.ambox-content {
/* @noflip */
border-left: 10px solid #f28500; /* Orange */
}
.ambox-style {
/* @noflip */
border-left: 10px solid #f4c430; /* Yellow */
}
.ambox-good {
border-left: 10px solid #66cc44;
}
.ambox-discussion {
border-left: 10px solid #339966;
}
.ambox-merge {
border-left: 10px solid #9932cc;
}
.ambox-move {
/* @noflip */
border-left: 10px solid #9932cc; /* Purple */
}
.ambox-protection {
/* @noflip */
border-left: 10px solid #a2a9b1; /* Gray-gold */
}
/* Footer and header message box styles */
.fmbox {
clear: both;
margin: 0.2em 0;
width: 100%;
border: 1px solid #aaa;
/* Default "system" gray */
background: #f9f9f9;
}
.fmbox-system {
background: #f9f9f9;
}
.fmbox-warning {
border: 1px solid #bb7070; /* Dark pink */
background: #ffdbdb; /* Pink */
}
.fmbox-editnotice {
background: transparent;
}
/* Div based "warning" style fmbox messages. */
div.mw-warning-with-logexcerpt,
div.mw-lag-warn-high,
div.mw-cascadeprotectedwarning,
div#mw-protect-cascadeon {
border: 1px solid #bb7070;
background: #ffdbdb;
}
/* These mbox-small classes must be placed after all other
ambox/tmbox/ombox etc classes. "body.mediawiki" is so
they override "table.ambox + table.ambox" above. */
.mediawiki .mbox-small.mbox-small { /* For the "small=yes" option. */
/* @noflip */
clear: right;
/* @noflip */
float: right;
/* @noflip */
margin: 4px 0 4px 1em;
width: 238px;
font-size: 88%;
line-height: 1.25em;
}
.mediawiki .mbox-small.mbox-small-left { /* For the "small=left" option. */
/* @noflip */
margin: 4px 1em 4px 0;
width: 238px;
border-collapse: collapse;
font-size: 88%;
line-height: 1.25em;
}
/* Style for {{rq}} */
/* Hide the extra cells */
.ambox-multiple_issues .ambox .mbox-image,
.ambox-multiple_issues .ambox .mbox-imageright,
.ambox-multiple_issues .ambox .mbox-empty-cell,
.ambox-multiple_issues .ambox .mbox-text-div,
.ambox-multiple_issues .ambox .mbox-textsmall-div {
display: none;
}
/* Remove borders, backgrounds, padding, etc. */
.ambox-multiple_issues .ambox {
border: none;
border-collapse: collapse;
background: transparent;
margin: 0 0 0 1.6em;
padding: 0;
width: auto;
display: block;
}
.ambox-multiple_issues .mbox-small-left {
font-size: 100%;
width: auto;
margin: 0;
}
/* Style the text cell as a list item and remove its padding */
.ambox-multiple_issues .ambox .mbox-text {
padding: 0;
margin: 0;
}
.ambox-multiple_issues .ambox .mbox-multiply {
display: list-item;
line-height: 1.5em;
list-style-image: url(/w/skins/Vector/resources/common/images/bullet-icon.svg);
}
.skin-monobook .ambox-multiple_issues .ambox .mbox-multiply {
list-style-type: square;
list-style-image: url(/w/skins/MonoBook/resources/images/bullet.svg);
}
/* Allow for hiding text in compact form */
.ambox-multiple_issue .hide-when-compact {
display: none;
}
/* Стили нотификаций для ноутбуков */
@media (max-width: 1366px) {
.ombox,
.tmbox,
.ambox {
margin-left: 6%;
margin-right: 6%;
}
}
/* Стили нотификаций для мобильного устройсва */
@media (max-width: 719px) {
.ombox,
.tmbox,
.ambox {
margin-left: 0;
margin-right: 0;
}
}
11cb8d0cac390752f622ee0a68b669c68a4aad50
Модуль:Message box
828
3
4
2024-04-29T01:21:42Z
Genka Barboskin
2
Новая страница: «-- This is a meta-module for producing message box templates, including -- {{mbox}}, {{ambox}}, {{imbox}}, {{tmbox}}, {{ombox}}, {{cmbox}} and {{fmbox}}. -- Load necessary modules. require('strict') local getArgs local categoryHandler = require('Module:Category handler')._main local yesno = require('Module:Yesno') local boxDate = require('Module:Calendar').bxDate; -- Get a language object for formatDate and ucfirst. local lang = mw.language.getContentLangu...»
Scribunto
text/plain
-- This is a meta-module for producing message box templates, including
-- {{mbox}}, {{ambox}}, {{imbox}}, {{tmbox}}, {{ombox}}, {{cmbox}} and {{fmbox}}.
-- Load necessary modules.
require('strict')
local getArgs
local categoryHandler = require('Module:Category handler')._main
local yesno = require('Module:Yesno')
local boxDate = require('Module:Calendar').bxDate;
-- Get a language object for formatDate and ucfirst.
local lang = mw.language.getContentLanguage()
-- Define constants
local CONFIG_MODULE = 'Module:Message box/configuration'
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
local function getTitleObject(...)
-- Get the title object, passing the function through pcall
-- in case we are over the expensive function count limit.
local success, title = pcall(mw.title.new, ...)
if success then
return title
end
end
local function union(t1, t2)
-- Returns the union of two arrays.
local vals = {}
for i, v in ipairs(t1) do
vals[v] = true
end
for i, v in ipairs(t2) do
vals[v] = true
end
local ret = {}
for k in pairs(vals) do
table.insert(ret, k)
end
table.sort(ret)
return ret
end
local function getArgNums(args, prefix)
local nums = {}
for k, v in pairs(args) do
local num = mw.ustring.match(tostring(k), '^' .. prefix .. '([1-9]%d*)$')
if num then
table.insert(nums, tonumber(num))
end
end
table.sort(nums)
return nums
end
-- локальная обёртка, игнорирует таблицу с номерами дня, месяца и года
local function formatDate(txtDateIn, strFormat, params)
local txtDateOut, date, status = boxDate(txtDateIn, strFormat, params)
if status.brk then
return error(status.errorText)
else
return txtDateOut
end
end
--------------------------------------------------------------------------------
-- Box class definition
--------------------------------------------------------------------------------
local MessageBox = {}
MessageBox.__index = MessageBox
function MessageBox.new(boxType, args, cfg)
args = args or {}
local obj = {}
-- Set the title object and the namespace.
obj.title = getTitleObject(args.page) or mw.title.getCurrentTitle()
-- Set the config for our box type.
obj.cfg = cfg[boxType]
if not obj.cfg then
local ns = obj.title.namespace
-- boxType is "mbox" or invalid input
if ns == 0 then
obj.cfg = cfg.ambox -- main namespace
elseif ns == 6 then
obj.cfg = cfg.imbox -- file namespace
elseif ns == 14 then
obj.cfg = cfg.cmbox -- category namespace
else
local nsTable = mw.site.namespaces[ns]
if nsTable and nsTable.isTalk then
obj.cfg = cfg.tmbox -- any talk namespace
else
obj.cfg = cfg.ombox -- other namespaces or invalid input
end
end
end
-- Set the arguments, and remove all blank arguments except for the ones
-- listed in cfg.allowBlankParams.
do
local newArgs = {}
for k, v in pairs(args) do
if v ~= '' then
newArgs[k] = v
end
end
for i, param in ipairs(obj.cfg.allowBlankParams or {}) do
newArgs[param] = args[param]
end
obj.args = newArgs
end
-- Define internal data structure.
obj.categories = {}
obj.classes = {}
return setmetatable(obj, MessageBox)
end
function MessageBox:addCat(ns, cat, sort)
if not cat then
return nil
end
if sort then
cat = string.format('[[Категория:%s|%s]]', cat, sort)
else
cat = string.format('[[Категория:%s]]', cat)
end
self.categories[ns] = self.categories[ns] or {}
table.insert(self.categories[ns], cat)
end
function MessageBox:addClass(class)
if not class then
return nil
end
table.insert(self.classes, class)
end
function MessageBox:setParameters()
local args = self.args
local cfg = self.cfg
-- Get type data.
self.type = args.type
local typeData = cfg.types[self.type]
self.invalidTypeError = cfg.showInvalidTypeError
and self.type
and not typeData
typeData = typeData or cfg.types[cfg.default]
self.typeClass = typeData.class
self.typeImage = typeData.image
-- Find if the box has been wrongly substituted.
self.isSubstituted = cfg.substCheck and args.subst == 'SUBST'
-- Find whether we are using a small message box.
self.isSmall = cfg.allowSmall and (
cfg.smallParam and args.small == cfg.smallParam
or not cfg.smallParam and yesno(args.small)
)
-- Add attributes, classes and styles.
self.id = args.id
self.name = args.name
if self.name then
self:addClass('mbox-' .. string.gsub(self.name,' ','_'))
end
if yesno(args.plainlinks) ~= false then
self:addClass('plainlinks')
end
for _, class in ipairs(cfg.classes or {}) do
self:addClass(class)
end
if self.isSmall then
self:addClass(cfg.smallClass or 'mbox-small')
end
self:addClass(self.typeClass)
self:addClass(args.class)
self.style = args.style
self.attrs = args.attrs
self.dataLabel1 = args['data-label-1']
self.dataLabel2 = args['data-label-2']
self.dataLabel3 = args['data-label-3']
self.dataValue1 = args['data-value-1']
self.dataValue2 = args['data-value-2']
self.dataValue3 = args['data-value-3']
-- Set text style.
self.textstyle = args.textstyle
-- Find if we are on the template page or not. This functionality is only
-- used if useCollapsibleTextFields is set, or if both cfg.templateCategory
-- and cfg.templateCategoryRequireName are set.
self.useCollapsibleTextFields = cfg.useCollapsibleTextFields
if self.useCollapsibleTextFields
or cfg.templateCategory
and cfg.templateCategoryRequireName
then
self.name = args.name
if self.name then
local templateName = mw.ustring.match(
self.name,
'^[tT][eE][mM][pP][lL][aA][tT][eE][%s_]*:[%s_]*(.*)$'
) or self.name
templateName = ('Template:' .. templateName) or ('Шаблон:' .. templateName)
self.templateTitle = getTitleObject(templateName)
end
self.isTemplatePage = self.templateTitle
and mw.title.equals(self.title, self.templateTitle)
end
-- Process data for collapsible text fields. At the moment these are only
-- used in {{ambox}}.
if self.useCollapsibleTextFields then
-- Get the self.issue value.
if self.isSmall and args.smalltext then
self.issue = args.smalltext
else
if args.sect and args.sect ~= '' or nil then
local issue_sect = args.issue_sect
issue_sect = type(issue_sect) == 'string' and issue_sect ~= '' and issue_sect or nil
local text_sect = args.text_sect
text_sect = type(text_sect) == 'string' and text_sect ~= '' and text_sect or nil
local issues = {}
table.insert(issues, issue_sect)
table.insert(issues, text_sect)
self.issue = table.concat(issues, ' ')
else
local issue = args.issue
issue = type(issue) == 'string' and issue ~= '' and issue or nil
local text = args.text
text = type(text) == 'string' and text or nil
local issues = {}
table.insert(issues, issue)
table.insert(issues, text)
self.issue = table.concat(issues, ' ')
end
end
-- Get the self.talk value.
local talk = args.talk
-- Show talk links on the template page or template subpages if the talk
-- parameter is blank.
if talk == ''
and self.templateTitle
and (
mw.title.equals(self.templateTitle, self.title)
or self.title:isSubpageOf(self.templateTitle)
)
then
talk = '#'
elseif talk == '' then
talk = nil
end
if talk then
-- If the talk value is a talk page, make a link to that page. Else
-- assume that it's a section heading, and make a link to the talk
-- page of the current page with that section heading.
local talkTitle = getTitleObject(talk)
local talkArgIsTalkPage = true
if not talkTitle or not talkTitle.isTalkPage then
talkArgIsTalkPage = false
talkTitle = getTitleObject(
self.title.text,
mw.site.namespaces[self.title.namespace].talk.id
)
end
if talkTitle and talkTitle.exists then
local talkText = 'Соответствующую дискуссию можно найти на'
if talkArgIsTalkPage then
talkText = string.format(
'%s [[%s|%s]].',
talkText,
talk,
talkTitle.prefixedText
)
else
talkText = string.format(
'%s [[%s#%s|странице обсуждения]].',
talkText,
talkTitle.prefixedText,
talk
)
end
self.talk = talkText
end
end
-- Get other values.
self.fix = args.fix ~= '' and args.fix or nil
local date
if args.date and args.date ~= '' then
local status, result = pcall(formatDate, args.date)
if status then
date = string.format("(<span class='date'>%s</span>)", result)
else
date = string.format("<span class='error'>(Строка «%s» не является верной датой, пожалуйста, укажите дату в формате <code>ГГГГ-ММ-ДД</code>)</span>", args.date)
end
elseif args.date == '' and self.isTemplatePage then
date = string.format("(<span class='date'>%s</span>)", formatDate( lang:formatDate('Y-m-d') ) ) -- тут возникновения ошибки, связанной с пользовательским вводом, не будет
end
if date then
self.date = string.format(" <span class='mbox-date'>''%s''</span>", date)
end
self.info = args.info
if yesno(args.removalnotice) then
self.removalNotice = cfg.removalNotice
end
if args.shortFix then
self.shortFix = args.shortFix
end
end
-- Set the non-collapsible text field. At the moment this is used by all box
-- types other than ambox, and also by ambox when small=yes.
if self.isSmall then
self.text = args.smalltext or args.text
else
self.text = args.text
self.textsmall = args['text-small']
end
-- Set the below row.
self.below = cfg.below and args.below
-- General image settings.
self.imageCellDiv = not self.isSmall and cfg.imageCellDiv
self.imageEmptyCell = cfg.imageEmptyCell
if cfg.imageEmptyCellStyle then
self.imageEmptyCellStyle = 'border:none;padding:0px;width:1px'
end
-- Left image settings.
local imageLeft = self.isSmall and args.smallimage or args.image
if cfg.imageCheckBlank and imageLeft ~= 'blank' and imageLeft ~= 'none' and imageLeft ~= ''
or not cfg.imageCheckBlank and imageLeft ~= 'none'
then
self.imageLeft = imageLeft
if not imageLeft then
local imageSize = self.isSmall
and (cfg.imageSmallSize or '30x30px')
or cfg.imageSize
or '40x40px'
self.imageLeft = string.format('[[File:%s|%s|alt=]]', self.typeImage
or 'Information icon4.svg', imageSize)
end
end
-- Right image settings.
local imageRight = self.isSmall and args.smallimageright or args.imageright
if not (cfg.imageRightNone and imageRight == 'none') then
self.imageRight = imageRight
end
-- set templatestyles
self.base_templatestyles = cfg.templatestyles
end
function MessageBox:setMainspaceCategories()
local args = self.args
local cfg = self.cfg
local date = nil
if not cfg.allowMainspaceCategories then
return nil
end
local nums = {}
for _, prefix in ipairs{'cat', 'category', 'all'} do
args[prefix .. '1'] = args[prefix]
nums = union(nums, getArgNums(args, prefix))
end
-- The following is roughly equivalent to the old {{Ambox/category}}.
local status, result = pcall(formatDate, args.date, 'xg Y')
if status then
date = result
end
date = type(date) == 'string' and date
local preposition = 'с'
local suffix = 'года'
for _, num in ipairs(nums) do
local mainCat = args['cat' .. tostring(num)]
or args['category' .. tostring(num)]
local allCat = args['all' .. tostring(num)]
mainCat = type(mainCat) == 'string' and mainCat
allCat = type(allCat) == 'string' and allCat
if mainCat and date and date ~= '' then
local catTitle = string.format('%s %s %s %s', mainCat, preposition, date, suffix)
self:addCat(0, catTitle)
catTitle = getTitleObject('Категория:' .. catTitle)
local status, result = pcall(formatDate, args.date)
if not status then
self:addCat(0, 'Википедия:Статьи с недопустимым параметром даты в шаблоне-сообщении')
end
elseif mainCat and (not date or date == '') then
self:addCat(0, mainCat)
end
if allCat then
self:addCat(0, allCat)
end
end
end
function MessageBox:setTemplateCategories()
local args = self.args
local cfg = self.cfg
-- Add template categories.
if cfg.templateCategory then
if cfg.templateCategoryRequireName then
if self.isTemplatePage then
self:addCat(10, cfg.templateCategory)
end
elseif not self.title.isSubpage then
self:addCat(10, cfg.templateCategory)
end
end
-- Add template error categories.
if cfg.templateErrorCategory then
local templateErrorCategory = cfg.templateErrorCategory
local templateCat, templateSort
if not self.name and not self.title.isSubpage then
templateCat = templateErrorCategory
elseif self.isTemplatePage then
local paramsToCheck = cfg.templateErrorParamsToCheck or {}
local count = 0
for i, param in ipairs(paramsToCheck) do
if not args[param] then
count = count + 1
end
end
if count > 0 then
templateCat = templateErrorCategory
templateSort = tostring(count)
end
if self.categoryNums and #self.categoryNums > 0 then
templateCat = templateErrorCategory
templateSort = 'C'
end
end
self:addCat(10, templateCat, templateSort)
end
end
function MessageBox:setAllNamespaceCategories()
-- Set categories for all namespaces.
if self.invalidTypeError then
local allSort = (self.title.namespace == 0 and 'Main:' or '') .. self.title.prefixedText
self:addCat('all', 'Википедия:Необходимо исправить параметр в шаблоне-сообщении', allSort)
end
if self.isSubstituted then
self:addCat('all', 'Википедия:Страницы с ошибочно подставленными шаблонами')
end
if self.isSmall then
self:addCat(0, 'Википедия:Страницы с малыми шаблонами-сообщениями')
end
end
function MessageBox:setCategories()
if self.title.namespace == 0 then
self:setMainspaceCategories()
elseif self.title.namespace == 10 then
self:setTemplateCategories()
end
self:setAllNamespaceCategories()
end
function MessageBox:renderCategories()
-- Convert category tables to strings and pass them through
-- [[Module:Category handler]].
return categoryHandler{
main = table.concat(self.categories[0] or {}),
template = table.concat(self.categories[10] or {}),
all = table.concat(self.categories.all or {}),
nocat = self.args.nocat,
page = self.args.page
}
end
function MessageBox:export()
local root = mw.html.create()
-- Add the subst check error.
if self.isSubstituted and self.name then
root:tag('b')
:addClass('error')
:wikitext(string.format(
'Шаблон <code>%s[[Шаблон:%s|%s]]%s</code> был неккоректно подставлен.',
mw.text.nowiki('{{'), self.name, self.name, mw.text.nowiki('}}')
))
end
-- Conditional TemplateStyles loading
if self.base_templatestyles then
local frame = mw.getCurrentFrame()
root:wikitext(frame:extensionTag{
name = 'templatestyles',
args = { src = self.base_templatestyles },
})
end
-- Create the box table.
local boxTable = root:tag('table')
boxTable:attr('id', self.id or nil)
for i, class in ipairs(self.classes or {}) do
boxTable:addClass(class or nil)
end
boxTable
:cssText(self.style or nil)
:attr('role', 'presentation')
if self.dataLabel1 then
boxTable:attr('data-' .. self.dataLabel1, self.dataValue1)
end
if self.dataLabel2 then
boxTable:attr('data-' .. self.dataLabel2, self.dataValue2)
end
if self.dataLabel3 then
boxTable:attr('data-' .. self.dataLabel3, self.dataValue3)
end
if self.attrs then
boxTable:attr(self.attrs)
end
-- Add the left-hand image.
local row = boxTable:tag('tr')
if self.imageLeft then
local imageLeftCell = row:tag('td'):addClass('mbox-image')
if self.imageCellDiv then
-- If we are using a div, redefine imageLeftCell so that the image
-- is inside it. Divs use style="width: 52px;", which limits the
-- image width to 52px. If any images in a div are wider than that,
-- they may overlap with the text or cause other display problems.
imageLeftCell = imageLeftCell:tag('div'):css('width', '52px')
end
imageLeftCell:wikitext(self.imageLeft or nil)
elseif self.imageEmptyCell then
-- Some message boxes define an empty cell if no image is specified, and
-- some don't. The old template code in templates where empty cells are
-- specified gives the following hint: "No image. Cell with some width
-- or padding necessary for text cell to have 100% width."
row:tag('td')
:addClass('mbox-empty-cell')
:cssText(self.imageEmptyCellStyle or nil)
end
-- Add the text.
local textCell = row:tag('td'):addClass('mbox-text')
if self.useCollapsibleTextFields then
-- The message box uses advanced text parameters that allow things to be
-- collapsible. At the moment, only ambox uses this.
textCell:cssText(self.textstyle or nil)
local textCellDiv = textCell:tag('div')
textCellDiv
:addClass('mbox-text-div')
:wikitext(self.issue or nil)
local textsmallCellDiv = textCell:tag('div')
textsmallCellDiv
:addClass('mbox-textsmall-div hide-when-compact')
:cssText(self.textsmallstyle)
:wikitext(self.textsmall or nil)
if (self.talk or self.fix) and not self.isSmall then
textsmallCellDiv:tag('span')
:addClass('hide-when-compact')
:wikitext(self.fix and (' ' .. self.fix) or nil)
:wikitext(self.talk and (' ' .. self.talk) or nil)
end
if self.textsmall or self.fix or self.talk then
textsmallCellDiv:wikitext(self.date and (' ' .. self.date) or nil)
else
textCellDiv:wikitext(self.date and (' ' .. self.date) or nil)
end
if self.info and not self.isSmall then
textsmallCellDiv
:tag('span')
:addClass('hide-when-compact')
:wikitext(self.info and (' ' .. self.info) or nil)
end
if self.removalNotice then
textsmallCellDiv:tag('small')
:addClass('hide-when-compact')
:tag('i')
:wikitext(string.format(" (%s)", self.removalNotice))
end
if self.shortFix then
textCell:tag('div')
:addClass('mbox-multiply')
:tag('span')
:wikitext(string.format("%s", self.shortFix))
:tag('span')
:wikitext(self.date and (' ' .. self.date) or nil)
end
else
-- Default text formatting - anything goes.
textCell
:cssText(self.textstyle or nil)
:wikitext(self.text or nil)
end
-- Add the right-hand image.
if self.imageRight then
local imageRightCell = row:tag('td'):addClass('mbox-imageright')
if self.imageCellDiv then
-- If we are using a div, redefine imageRightCell so that the image
-- is inside it.
imageRightCell = imageRightCell:tag('div'):css('width', '52px')
end
imageRightCell
:wikitext(self.imageRight or nil)
end
-- Add the below row.
if self.below then
boxTable:tag('tr')
:tag('td')
:attr('colspan', self.imageRight and '3' or '2')
:addClass('mbox-text')
:cssText(self.textstyle or nil)
:wikitext(self.below or nil)
end
-- Add error message for invalid type parameters.
if self.invalidTypeError then
root:tag('div')
:css('text-align', 'center')
:wikitext(string.format(
'Этот шаблон-сообщение использует неверный параметр "type=%s", необходимо исправить.',
self.type or ''
))
end
-- Add categories.
root:wikitext(self:renderCategories() or nil)
return tostring(root)
end
--------------------------------------------------------------------------------
-- Exports
--------------------------------------------------------------------------------
local p, mt = {}, {}
function p._exportClasses()
-- For testing.
return {
MessageBox = MessageBox
}
end
function p.main(boxType, args, cfgTables)
local box = MessageBox.new(boxType, args, cfgTables or mw.loadData(CONFIG_MODULE))
box:setParameters()
box:setCategories()
return box:export()
end
function mt.__index(t, k)
return function (frame)
if not getArgs then
getArgs = require('Module:Arguments').getArgs
end
return t.main(k, getArgs(frame, {trim = false, removeBlanks = false}))
end
end
return setmetatable(p, mt)
f2539b657a9cdadde7c0dd5ad270d3095b2bdd54
Шаблон:Ambox
10
4
5
2024-04-29T01:24:29Z
Genka Barboskin
2
Новая страница: «{{#invoke:Message box|ambox}}{{#ifeq:{{{small}}}|left|[[Категория:Страницы, использующие малые шаблоны-сообщения]]}}<noinclude> {{doc}} <!-- Categories go on the /doc subpage, and interwikis go on Wikidata. --> </noinclude>»
wikitext
text/x-wiki
{{#invoke:Message box|ambox}}{{#ifeq:{{{small}}}|left|[[Категория:Страницы, использующие малые шаблоны-сообщения]]}}<noinclude>
{{doc}}
<!-- Categories go on the /doc subpage, and interwikis go on Wikidata. -->
</noinclude>
5345bd7c0e2430e3672a54d920abd0f0bf61dc61
19
5
2024-04-29T03:19:19Z
Genka Barboskin
2
wikitext
text/x-wiki
{{#invoke:Message box|ambox}}{{#ifeq:{{{small}}}|left|[[Категория:Страницы, использующие малые шаблоны-сообщения]]}}<noinclude>
<!-- Categories go on the /doc subpage, and interwikis go on Wikidata. -->
</noinclude>
4361ec2a7d0e0949292b3087e9fff4b9b30f5647
Модуль:Category handler
828
5
6
2024-04-29T03:00:30Z
Genka Barboskin
2
Новая страница: «-------------------------------------------------------------------------------- -- -- -- CATEGORY HANDLER -- -- -- -- This module implements the {{category handler}} template in Lua, -- -- with a few improvements: all namespaces and all n...»
Scribunto
text/plain
--------------------------------------------------------------------------------
-- --
-- CATEGORY HANDLER --
-- --
-- This module implements the {{category handler}} template in Lua, --
-- with a few improvements: all namespaces and all namespace aliases --
-- are supported, and namespace names are detected automatically for --
-- the local wiki. This module requires [[Module:Namespace detect]] --
-- and [[Module:Yesno]] to be available on the local wiki. It can be --
-- configured for different wikis by altering the values in --
-- [[Module:Category handler/config]], and pages can be blacklisted --
-- from categorisation by using [[Module:Category handler/blacklist]]. --
-- --
--------------------------------------------------------------------------------
-- Load required modules
local yesno = require('Module:Yesno')
-- Lazily load things we don't always need
local mShared, mappings
local p = {}
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
local function trimWhitespace(s, removeBlanks)
if type(s) ~= 'string' then
return s
end
s = s:match('^%s*(.-)%s*$')
if removeBlanks then
if s ~= '' then
return s
else
return nil
end
else
return s
end
end
--------------------------------------------------------------------------------
-- CategoryHandler class
--------------------------------------------------------------------------------
local CategoryHandler = {}
CategoryHandler.__index = CategoryHandler
function CategoryHandler.new(data, args)
local obj = setmetatable({ _data = data, _args = args }, CategoryHandler)
-- Set the title object
do
local pagename = obj:parameter('demopage')
local success, titleObj
if pagename then
success, titleObj = pcall(mw.title.new, pagename)
end
if success and titleObj then
obj.title = titleObj
if titleObj == mw.title.getCurrentTitle() then
obj._usesCurrentTitle = true
end
else
obj.title = mw.title.getCurrentTitle()
obj._usesCurrentTitle = true
end
end
-- Set suppression parameter values
for _, key in ipairs{'nocat', 'categories'} do
local value = obj:parameter(key)
value = trimWhitespace(value, true)
obj['_' .. key] = yesno(value)
end
do
local subpage = obj:parameter('subpage')
local category2 = obj:parameter('category2')
if type(subpage) == 'string' then
subpage = mw.ustring.lower(subpage)
end
if type(category2) == 'string' then
subpage = mw.ustring.lower(category2)
end
obj._subpage = trimWhitespace(subpage, true)
obj._category2 = trimWhitespace(category2) -- don't remove blank values
end
return obj
end
function CategoryHandler:parameter(key)
local parameterNames = self._data.parameters[key]
local pntype = type(parameterNames)
if pntype == 'string' or pntype == 'number' then
return self._args[parameterNames]
elseif pntype == 'table' then
for _, name in ipairs(parameterNames) do
local value = self._args[name]
if value ~= nil then
return value
end
end
return nil
else
error(string.format(
'invalid config key "%s"',
tostring(key)
), 2)
end
end
function CategoryHandler:isSuppressedByArguments()
return
-- See if a category suppression argument has been set.
self._nocat == true
or self._categories == false
or (
self._category2
and self._category2 ~= self._data.category2Yes
and self._category2 ~= self._data.category2Negative
)
-- Check whether we are on a subpage, and see if categories are
-- suppressed based on our subpage status.
or self._subpage == self._data.subpageNo and self.title.isSubpage
or self._subpage == self._data.subpageOnly and not self.title.isSubpage
end
function CategoryHandler:shouldSkipBlacklistCheck()
-- Check whether the category suppression arguments indicate we
-- should skip the blacklist check.
return self._nocat == false
or self._categories == true
or self._category2 == self._data.category2Yes
end
function CategoryHandler:matchesBlacklist()
if self._usesCurrentTitle then
return self._data.currentTitleMatchesBlacklist
else
mShared = mShared or require('Module:Category handler/shared')
return mShared.matchesBlacklist(
self.title.prefixedText,
mw.loadData('Module:Category handler/blacklist')
)
end
end
function CategoryHandler:isSuppressed()
-- Find if categories are suppressed by either the arguments or by
-- matching the blacklist.
return self:isSuppressedByArguments()
or not self:shouldSkipBlacklistCheck() and self:matchesBlacklist()
end
function CategoryHandler:getNamespaceParameters()
if self._usesCurrentTitle then
return self._data.currentTitleNamespaceParameters
else
if not mappings then
mShared = mShared or require('Module:Category handler/shared')
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
end
return mShared.getNamespaceParameters(
self.title,
mappings
)
end
end
function CategoryHandler:namespaceParametersExist()
-- Find whether any namespace parameters have been specified.
-- We use the order "all" --> namespace params --> "other" as this is what
-- the old template did.
if self:parameter('all') then
return true
end
if not mappings then
mShared = mShared or require('Module:Category handler/shared')
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
end
for ns, params in pairs(mappings) do
for i, param in ipairs(params) do
if self._args[param] then
return true
end
end
end
if self:parameter('other') then
return true
end
return false
end
function CategoryHandler:getCategories()
local params = self:getNamespaceParameters()
local nsCategory
for i, param in ipairs(params) do
local value = self._args[param]
if value ~= nil then
nsCategory = value
break
end
end
if nsCategory ~= nil or self:namespaceParametersExist() then
-- Namespace parameters exist - advanced usage.
if nsCategory == nil then
nsCategory = self:parameter('other')
end
local ret = {self:parameter('all')}
local numParam = tonumber(nsCategory)
if numParam and numParam >= 1 and math.floor(numParam) == numParam then
-- nsCategory is an integer
ret[#ret + 1] = self._args[numParam]
else
ret[#ret + 1] = nsCategory
end
if #ret < 1 then
return nil
else
return table.concat(ret)
end
elseif self._data.defaultNamespaces[self.title.namespace] then
-- Namespace parameters don't exist, simple usage.
return self._args[1]
end
return nil
end
--------------------------------------------------------------------------------
-- Exports
--------------------------------------------------------------------------------
local p = {}
function p._exportClasses()
-- Used for testing purposes.
return {
CategoryHandler = CategoryHandler
}
end
function p._main(args, data)
data = data or mw.loadData('Module:Category handler/data')
local handler = CategoryHandler.new(data, args)
if handler:isSuppressed() then
return nil
end
return handler:getCategories()
end
function p.main(frame, data)
data = data or mw.loadData('Module:Category handler/data')
local args = require('Module:Arguments').getArgs(frame, {
wrappers = data.wrappers,
valueFunc = function (k, v)
v = trimWhitespace(v)
if type(k) == 'number' then
if v ~= '' then
return v
else
return nil
end
else
return v
end
end
})
return p._main(args, data)
end
return p
b74dd63857b24904ac452429b11213f18647471f
Модуль:Yesno
828
6
7
2024-04-29T03:01:59Z
Genka Barboskin
2
Новая страница: «-- Function allowing for consistent treatment of boolean-like wikitext input. -- It works similarly to the template {{yesno}}. return function (val, default) -- If your wiki uses non-ascii characters for any of "yes", "no", etc., you -- should replace "val:lower()" with "mw.ustring.lower(val)" in the -- following line. val = type(val) == 'string' and val:lower() or val if val == nil then return nil elseif val == true or val == 'yes' or val == '...»
Scribunto
text/plain
-- Function allowing for consistent treatment of boolean-like wikitext input.
-- It works similarly to the template {{yesno}}.
return function (val, default)
-- If your wiki uses non-ascii characters for any of "yes", "no", etc., you
-- should replace "val:lower()" with "mw.ustring.lower(val)" in the
-- following line.
val = type(val) == 'string' and val:lower() or val
if val == nil then
return nil
elseif val == true
or val == 'yes'
or val == 'y'
or val == 'true'
or val == 't'
or val == 'да'
or val == 'д'
-- кириллица
or val == 'у'
or val == '+'
or tonumber(val) == 1
then
return true
elseif val == false
or val == 'no'
or val == 'n'
or val == 'false'
or val == 'f'
or val == 'нет'
or val == 'н'
or val == '-'
or tonumber(val) == 0
then
return false
else
return default
end
end
ae94e12a838e770797317ed07b57b330ffeb7658
Модуль:Calendar
828
7
8
2024-04-29T03:02:42Z
Genka Barboskin
2
Новая страница: «local p = {} -- Необходимые модули и переменные local getArgs = require('Module:Arguments').getArgs local yesno = require('Module:Yesno') local mwlang = mw.getContentLanguage() local err = "―" -- NthDay nil result local tCon = table.concat -- 00) Блок многократно используемых списков local bool_to_number={ [true]=1, [false]=0 } local monthlang = {"января","февраля","марта","а...»
Scribunto
text/plain
local p = {}
-- Необходимые модули и переменные
local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')
local mwlang = mw.getContentLanguage()
local err = "―" -- NthDay nil result
local tCon = table.concat
-- 00) Блок многократно используемых списков
local bool_to_number={ [true]=1, [false]=0 }
local monthlang = {"января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"}
local month_to_num = {["января"]=1,["февраля"]=2,["марта"]=3,["апреля"]=4,["мая"]=5,["июня"]=6,
["июля"]=7,["августа"]=8,["сентября"]=9,["октября"]=10,["ноября"]=11,["декабря"]=12,["-"]=""}
local monthd = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
local params = { {"г", "g"}, {"ю", "j"}}
local comment = { '<span style="border-bottom: 1px dotted; cursor: help" title="по юлианскому календарю">','</span>'}
-- duplicates:
-- AST, BST, CST, ECT, IST, MST, PST, SST,
local known_tzs = {
ACDT='+10:30', ACST='+09:30', ACT ='+08:00', ADT ='-03:00', AEDT ='+11:00',
AEST='+10:00', AFT ='+04:30', AKDT='-08:00', AKST ='-09:00', AMST ='+05:00',
AMT ='+04:00', ART ='-03:00', AST ='+03:00', AST ='+04:00', AST ='+03:00',
AST ='-04:00', AWDT='+09:00', AWST='+08:00', AZOST='-01:00', AZT ='+04:00',
BDT ='+08:00', BIOT='+06:00', BIT ='-12:00', BOT ='-04:00', BRT ='-03:00',
BST ='+06:00', BST ='+01:00', BTT ='+06:00', CAT ='+02:00', CCT ='+06:30',
CDT ='-05:00', CEDT='+02:00', CEST='+02:00', CET ='+01:00', CHAST='+12:45',
CIST='-08:00', CKT ='-10:00', CLST='-03:00', CLT ='-04:00', COST ='-04:00',
COT ='-05:00', CST ='-06:00', CST ='+08:00', CVT ='-01:00', CXT ='+07:00',
CHST='+10:00', DFT ='+01:00', EAST='-06:00', EAT ='+03:00', ECT ='-04:00',
ECT ='-05:00', EDT ='-04:00', EEDT='+03:00', EEST ='+03:00', EET ='+02:00',
EST ='-05:00', FJT ='+12:00', FKST='-03:00', FKT ='-04:00', GALT ='-06:00',
GET ='+04:00', GFT ='-03:00', GILT='+12:00', GIT ='-09:00', GMT ='+00:00',
GST ='-02:00', GYT ='-04:00', HADT='-09:00', HAST ='-10:00', HKT ='+08:00',
HMT ='+05:00', HST ='-10:00', IRKT='+08:00', IRST ='+03:30', IST ='+05:30',
IST ='+01:00', IST ='+02:00', JST ='+09:00', KRAT ='+07:00', KST ='+09:00',
LHST='+10:30', LINT='+14:00', MAGT='+11:00', MDT ='-06:00', MIT ='-09:30',
MSD ='+04:00', MSK ='+03:00', MST ='+08:00', MST ='-07:00', MST ='+06:30',
MUT ='+04:00', NDT ='-02:30', NFT ='+11:30', NPT ='+05:45', NST ='-03:30',
NT ='-03:30', OMST='+06:00', PDT ='-07:00', PETT ='+12:00', PHOT ='+13:00',
PKT ='+05:00', PST ='-08:00', PST ='+08:00', RET ='+04:00', SAMT ='+04:00',
SAST='+02:00', SBT ='+11:00', SCT ='+04:00', SLT ='+05:30', SST ='-11:00',
SST ='+08:00', TAHT='-10:00', THA ='+07:00', UTC ='+00:00', UYST ='-02:00',
UYT ='-03:00', VET ='-04:30', VLAT='+10:00', WAT ='+01:00', WEDT ='+01:00',
WEST='+01:00', WET ='+00:00', YAKT='+09:00', YEKT ='+05:00',
-- US Millitary (for RFC-822)
Z='+00:00', A='-01:00', M='-12:00', N='+01:00', Y='+12:00',
}
local category = {
["no_parameters"]=
"<!--[[Категория:Модуль:Calendar:Страницы без параметров]]-->",
["incomplete_parameters"]=
"<!--[[Категория:Модуль:Calendar:Страницы с неполными или некорректными параметрами]]-->",
["without_verification"]=
"<!--[[Категория:Модуль:Calendar:Страницы без проверки параметров]]-->",
["erroneous_parameters"]=
"<!--[[Категория:Модуль:Calendar:Страницы с ошибочными параметрами]]-->"
}
-- несколько параметров передаются вместе с кодом ошибки в таблице, один может быть передан простым значением
local e = {
["start"]="<span class=error>Ошибка: ",
["ending"]=".</span>",
["no_pattern_match"]="строка «%s» не совпадает с заданными паттернами",
["no_valid_date"]="дата «%s» не является корректной",
["wrong_jd"]="юлианская дата %s вне диапазона",
["no_data"]="нет входящих данных",
["too_many_arguments"]="ожидается менее %i аргументов",
["too_little_arguments"]="ожидается более %i аргументов",
["wrong_calculation"]="даты %s и %s не прошли проверку, %s дней разница",
["unknown_param"]="параметр %s неизвестен",
["unknown_error"]="неизвестная ошибка",
["tech_error"]="ошибка в функции %s",
["box_date"]="строка «%s» не является верной датой, пожалуйста, укажите дату в формате ГГГГ-ММ-ДД"
-- [""]="",
}
local tzs_names = {"ACDT","ACST","ACT","ADT","AEDT","AEST","AFT","AKDT","AKST",
"AMST","AMT","ART","AST","AST","AST","AST","AWDT","AWST","AZOST","AZT","BDT",
"BIOT","BIT","BOT","BRT","BST","BST","BTT","CAT","CCT","CDT","CEDT","CEST",
"CET","CHAST","CIST","CKT","CLST","CLT","COST","COT","CST","CST","CVT","CXT",
"CHST","DFT","EAST","EAT","ECT","ECT","EDT","EEDT","EEST","EET","EST","FJT",
"FKST","FKT","GALT","GET","GFT","GILT","GIT","GMT","GST","GYT","HADT","HAST",
"HKT","HMT","HST","IRKT","IRST","IST","IST","IST","JST","KRAT","KST","LHST",
"LINT","MAGT","MDT","MIT","MSD","MSK","MST","MST","MST","MUT","NDT","NFT",
"NPT","NST","NT","OMST","PDT","PETT","PHOT","PKT","PST","PST","RET","SAMT",
"SAST","SBT","SCT","SLT","SST","SST","TAHT","THA","UTC","UYST","UYT","VET",
"VLAT","WAT","WEDT","WEST","WET","YAKT","YEKT","Z","A","M","N","Y","MSK"}
local pattern = { -- для распознавания дат, переданных одним строчным параметром
{"(-?%d%d%d%d?)[-%.%s/\\](%d%d)[-%.%s/\\](%d%d)", ["order"] = {3,2,1} }, -- yyyy mm dd
{"(%d+)[-%.%s/\\](%d+)[-%.%s/\\](%d%d%d%d?)", ["order"] = {1,2,3} }, -- dd mm yyyy
{"(%d%d)[-%.%s/\\](%d%d%d%d?)", ["order"] = {2,3} }, -- mm yyyy
{"(%d%d%d%d?)[-%.%s/\\](%d%d)", ["order"] = {3,2} }, -- yyyy mm
{"(%d+)%s(%l+)%s(%d%d%d%d?)", ["order"] = {1,2,3} }, -- d mmm y
{"(%l+)%s(%d+),?%s(%d%d%d%d?)", ["order"] = {2,1,3} }, -- mmm d, y
{"(%l+)%s(%d%d%d%d?)", ["order"] = {2,3} }, -- mmm y
}
local time_units = {"year","month","day"} --не используется
--[[ local time_units = {"second", "minute", "hour",
"day_of_month", "day_of_week", "day_of_year",
"week", "month", "year", "year_of_century", "century"} ]]--
-- напоминание чтобы сделать более точные пересчёты - с часами / расчёт длительностей периодов
local mnlang = {"ru_G", "ru_N", "en", "en_S", "de", "fr"}
local month_lang = {
["ru_G"] = {"января","февраля","марта","апреля","мая","июня",
"июля","августа","сентября","октября","ноября","декабря"},
["ru_N"] = {"январь","февраль","март","апрель","май","июнь",
"июль","август","сентябрь","октябрь","ноябрь","декабрь"},
["en"] = {"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december"},
["en_S"] = {"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"},
["de"] = {"januar", "februar", "märz", "april", "mai", "juni",
"juli", "august", "september", "oktober", "november", "dezember"},
["fr"] = {"janvier", "février", "mars", "avril", "mai", "juin",
"juillet", "août", "septembre", "octobre", "novembre", "décembre"}
}
-- заполняется автоматически
local reverse_month_lang = {}
-- вспомогательная функция для обращения таблиц (смена ключей со значениями)
local reverse_table = function (strait_table)
local reversed_table = {}
for k,v in pairs(strait_table) do
reversed_table[v] = k
end
return reversed_table
end
-- запуск цикла по заполнению обратных таблиц, необходимых для распознавания дат
local filling_months = function (mnlang, month_lang)
for i=1, #mnlang do
reverse_month_lang[mnlang[i]] = reverse_table(month_lang[mnlang[i]])
end
end
-- 10) Блок общих функций
local function trim(str)
if not str then return nil
else return str:match'^()%s*$' and '' or str:match'^%s*(.*%S)'
end
end
local function purif(str)
if str == "" or str == nil then
return nil
elseif type(tonumber(str)) == "number" then
return math.floor(tonumber(str))
else
return nil
end
-- need .5 -- ,5 number format converter?
end
local function is(str)
if (not str) or (str == "") then return false
else return yesno(str,false)
end
end
local function init(num)
local output = {}
for i=1,num do
table.insert(output, {["year"]="", ["month"]="", ["day"]=""})
end
return unpack(output)
end
local function isyear(tbl)
if type(tbl) ~= 'table' then return false
elseif not tbl["year"] then return false
elseif type(tbl["year"]) == 'number' then return true
else return false
end
end
local function inbord(val, down, up)
return not (type(up) ~= "number" or type(down) ~= "number" or type(val) ~= "number" or up < down or val < down or val > up)
end
local function shallowcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
local inlist = function ( var, list )
local n = #list
local inlist = false
for i=1,n do
if var == list[i] then inlist = true end
end
return inlist
end
-- 20) Блок общих проверочных функций, связанных с датами
local function unwarp(tbl)
if not tbl then return ""
elseif type(tbl) ~= "table" then return tbl
elseif (tbl.day or tbl.month or tbl.year) then
return (tbl.year or "?").."-"..(tbl.month or "?").."-"..(tbl.day or "?")
else return (tbl[3] or "?").."-"..(tbl[2] or "?").."-"..(tbl[1] or "?")
end
end
local function leap_year(y,jul)
if (not y) or (type(y) ~= "number")
then return false
elseif (y % 4) ~= 0
then return false
elseif not jul and (y % 100 == 0 and y % 400 ~= 0)
then return false
else return true
end
end
-- функция для вычисления последнего дня месяца для юлианского и григорианского календарей
local function month_end_day (month,year,is_julian)
local month_end_day = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} -- если не задан год, дата 29 февраля считается допустимой
if not month or type(month) ~= "number" or month < 1 or month > 12 then return nil
elseif month ~= 2 or not year then return month_end_day[month]
elseif month == 2 and (year % 4) == 0 and not ((not is_julian) and (year % 100 == 0 and year % 400 ~= 0)) then return 29
elseif month == 2 then return 28
else return nil -- в случае не целого значения входящих параметров или при иных непредусмотренных событиях
end
end
local function isdate ( chain , jul ) -- можно использовать для проверки таблиц с полями day, month, year
if not chain then return false
elseif (not type(chain) == "table")
or (not inbord(chain.year,-9999,9999))
or (not inbord(chain.month,1,12))
or (not inbord(chain.day,1,31))
or chain.day > monthd[chain.month]
-- or chain.year == 0
then return false
elseif chain.month == 2 and chain.day == 29 and not leap_year(chain.year,jul)
then return false
else return true end
-- check for other calendars needed?
end
local function ispartdate ( chain )
if not chain then return false
elseif not (type(chain) == "table") then return false
elseif (inbord(chain.year,-9999,9999)
or inbord(chain.month,1,12)
or inbord(chain.day,1,31)) then return true
else return false
end
-- partial date
-- more detailed check for 31.02.0000 needed
-- check for other calendars needed
end
-- from date1 to date2 in one year (beetwen jan-dec, dec-jan needed)
local function partdist(date1,date2)
local mont, dist = 0, 0
local d1d, d1m, d2d, d2m = (date1["day"] or ""), (date1["month"] or ""),(date2["day"] or ""), (date2["month"] or "")
if not (inbord(d1d,1,31) and inbord(d2d,1,31)) then return false end
-- нужна доп. проверка частичных дат на корректность
if (inbord(d1m,1,12) or inbord(d2m,1,12))
and (d1m == "" or d2m == "") then
mont = purif(date1["month"] or date2["month"])
d1m, d2m = mont, mont
end
-- mw.log("📏 day: " ..d1d .."->"..d2d.." month: ".. d1m.."->"..d2m )
if (inbord(d1m,1,12) and d1d <= monthd[d1m])
and (inbord(d2m,1,12) and d2d <= monthd[d2m]) then
if d2m == d1m
then dist = d2d - d1d
else dist = monthd[d1m] - d1d + d2d
end
return dist
else return math.huge
end
end
local function dmdist(d1,d2)
local p1,p2 = math.huge,math.huge
if not not partdist(d1,d2) then
p1=partdist(d1,d2)
end
if not not partdist(d2,d1) then
p1=partdist(d2,d1)
end
-- if (not p1) or (not p2) then
-- return (p1 or "") .. (p2 or "")
-- else
-- mw.log("d1, d2 = " .. undate(d1) .. ", " .. undate(d2))
return math.min(tonumber(partdist(d1,d2)) or math.huge,tonumber(partdist(d2,d1)) or math.huge)
-- end
end
-- 30) Блок функций для обработки ввода-вывода дат
local function undate(tbl)
if not tbl then return ""
else return (tbl.year or "").."-"..(tbl.month or "").."-"..(tbl.day or "")
end
end
-- функция для нормализации значений дат и перевода месяцев в числа
local function numerize(str)
if type(str) == "number" then
return math.floor(str)
elseif str == "" or str == nil or type(str) ~= "string" then
return nil
elseif type(tonumber(str)) == "number" then
return math.floor(tonumber(str))
else
for i=1, #mnlang do
if inlist(mw.ustring.lower(str),month_lang[mnlang[i]]) then
return reverse_month_lang[mnlang[i]][mw.ustring.lower(str)]
end
end
end
end
-- функция распознавания даты, переданной одной строкой
local function parse_date(date_string)
if type(date_string) ~= "string" or date_string == "" then return nil end
local out_date_str = {"","",""}
local error_data = {}
for i=1, #pattern do
local result_1, result_2, result_3 = mw.ustring.match(mw.ustring.lower(date_string),pattern[i][1])
if (result_1 or "") > "" then
out_date_str[pattern[i].order[1]] = result_1
out_date_str[pattern[i].order[2]] = result_2
if (pattern[i].order[3]) then out_date_str[pattern[i].order[3]] = result_3 end
-- mw.log("Паттерн " .. i .. ", строка: " .. date_string)
break
end
end
local date = {
["day"] =numerize(out_date_str[1]),
["month"]=numerize(out_date_str[2]),
["year"] =numerize(out_date_str[3])}
return date --, error_data
end
----[[ УСТАРЕЛО ]]----
local numstr2date = function(numstr)
local format = "Y-m-d"
local iso_date = mwlang:formatDate(format,numstr)
local y,m,d = string.match(iso_date, "(%d+)-(%d+)-(%d+)")
local dateout = {["year"]=purif(y), ["month"]=purif(m), ["day"]=purif(d)}
return dateout
end
--local numstr2date = function(numstr)
-- local nums = {}
-- local dateout = {}
-- for num in string.gmatch(numstr,"(%d+)") do
-- table.insert(nums,purif(num))
-- end
-- if #nums ~= 3 then error("В поле даты вместо трёх чисел с разделителями указано " .. #nums)
-- elseif not inbord(nums[2],1,12) then error("Месяц с номером " .. nums[2] .. " не найден")
-- elseif not inbord(nums[3],1,31) then
-- dateout = {["year"]=nums[3], ["month"]=nums[2], ["day"]=nums[1]}
-- elseif not inbord(nums[1],1,31) then
-- dateout = {["year"]=nums[1], ["month"]=nums[2], ["day"]=nums[3]}
-- elseif inbord(nums[1],1,31) then
-- dateout = {["year"]=nums[3], ["month"]=nums[2], ["day"]=nums[1]}
-- else
-- local mwlang = mw.getContentLanguage()
-- implement mwlang:formatDate(format,datein,true) here
-- return error("Не распознано " .. numstr .. " как дата")
-- end
-- return dateout
--end
local function year2lang(numyear,yearmark,wiki)
if not numyear then return "" end
if not yearmark then yearmark = "" end
local output = ""
local bcmark = " до н. э."
if numyear > 0 then bcmark = ""
else numyear = 1 - numyear end
if wiki then
-- output = tCon({'[[', numyear,' год',bcmark,'|', numyear,']]', " ", yearmark, " ", bcmark})
output = tCon({'[[', numyear,' год',bcmark,'|', trim(numyear .. " " .. yearmark .. " " .. bcmark), ']]'})
else
output = tCon({numyear, " ", yearmark, bcmark})
end
return trim(output)
end
local function day2lang(datein,wikidate,wiki,inner_brt)
-- if not isdate(wikidate) then wiki = false end
if not ispartdate(datein) then return "" end
local dm_separ, output = "", nil
if (not (not datein.day)) and (not (not datein.month)) then dm_separ = " " end
if (not datein.month) then datein.month = "" end
if (not datein.day) then datein.day = "" end
local monlan = monthlang[datein.month] or ""
if wiki and not inner_brt then
output = tCon({"[[", wikidate.day, " ", monthlang[wikidate.month] or "",
"|", (datein.day or ""), dm_separ, monlan, "]]"})
elseif wiki then
output = tCon({"[[", wikidate.day, " ", monthlang[wikidate.month] or "",
"|", (datein.day or ""), dm_separ, monlan})
else
output = tCon({datein.day, dm_separ, monlan})
end
return trim(output)
end
local function triple_txt2date(d,m,y)
-- добавить (args[1]:match("(%a+)") or "-") для нестандартной записи
-- mw.ustring.match((m or ""),"(%a+)")
local msg = ""
local year = purif((y or "-"):match("(%d+)"))
local month = purif(month_to_num[string.lower(mw.ustring.match((m or ""),"(%a+)"))])
local day = purif((d or "-"):match("(%d+)"))
if not month then
msg = category.incomplete_parameters
month = purif(month_to_num[string.lower(mw.ustring.match((d or ""),"(%a+)") or "-")])
end
if (not day) and ((purif(string.match(m or "","(%d+)") or "") or 32) <= (monthd[month] or 31)) then
msg = category.incomplete_parameters
day = purif(m:match("(%d+)") or "")
end
if not year then
msg = category.incomplete_parameters
year = purif(string.match(m or "","(%d+)") or "")
end
local dateout = {["year"]=year, ["month"]=month, ["day"]=day, ["msg"]=msg}
return dateout
end
local function glue(d1,m1,y1,d2,m2,y2)
if (not d1) and (not m1) and (not y1) and (not d2) and (not m2) and (not y2) then
return category.incomplete_parameters end
local gd,gm,gy,jd,jm,jy =
(d1 or ""),
(m1 or ""),
(y1 or ""),
(d2 or ""),
(m2 or ""),
(y2 or "")
--mw.log(tCon({gd,gm,gy,jd,jm,jy}))
local gm_sep = {" [["," год|","]]"}
if (not gy) or (gy == "") then gm_sep = {"","",""} end
return tCon({comment[1],trim(trim(jd .. " " .. jm) .. " " .. jy ),
comment[2]," ([[",trim(gd .. " " .. gm),"]]",gm_sep[1],(gy:match("(%d+)") or ""),
gm_sep[2],gy,gm_sep[3],")",category.incomplete_parameters})
end
-- добавить отображение без года
local function double_couple(jdate, gdate, wd, wm, wy, sq_brts, yearmark)
local msg = ""
msg = (jdate.msg or "") .. (gdate.msg or "")
local cd = {}
local jd = shallowcopy(jdate)
local gd = shallowcopy(gdate)
local left = "("
local right = ")"
if sq_brts then
left = "["
right = "]"
end
if (not isdate(jdate,true)) then return error((jdate.day or "") .. "." .. (jdate.month or "") .."." .. (jdate.year or "") .. " неподходящая дата")
elseif (not isdate(gdate)) then return error((gdate.day or "") .. "." .. (gdate.month or "") .."." .. (gdate.year or "") .. " неподходящая дата") end
if jd.year == gd.year then
cd.year = gd.year
gd.year, jd.year = nil, nil
end
if jd.month == gd.month then
cd.month = gd.month
gd.month, jd.month = nil, nil
end
if (not not cd.month) and wm then
return tCon({comment[1] .. trim(day2lang(jd,jdate,false) .. " " .. year2lang(jd.year,yearmark,false)) .. comment[2],
trim(left .. day2lang(gd,gdate,wd,wm) .. " " .. year2lang(gd.year,yearmark,wy)) .. right,
day2lang(cd,gdate,false) .. "]]", trim(year2lang(cd.year,yearmark,wy)..msg)}, " ")
end
return tCon({comment[1] .. trim(day2lang(jd,jdate,false) .. " " .. year2lang(jd.year,yearmark,false)) .. comment[2],
trim(left .. day2lang(gd,gdate,wd) .. " " .. year2lang(gd.year,yearmark,wy)) .. right,
trim(day2lang(cd,gdate,false)), trim(year2lang(cd.year,yearmark,wy)..msg)}, " ")
end
-- 40) Блок функций для перевода дат с использованием [[Юлианская дата]]
local function gri2jd( datein )
if not isdate(datein) then return error((datein.day or "") .. "." .. (datein.month or "") .."." .. (datein.year or "") .. " неподходящая дата") end
local year = datein.year
local month = datein.month
local day = datein.day
-- jd calculation
local a = math.floor((14 - month)/12)
local y = year + 4800 - a
local m = month + 12*a - 3
local offset = math.floor(y/4) - math.floor(y/100) + math.floor(y/400) - 32045
local jd = day + math.floor((153*m + 2)/5) + 365*y + offset
-- jd validation
local low, high = -1931076.5, 5373557.49999
if not (low <= jd and jd <= high) then
return error((datein.day or "") .. "." .. (datein.month or "") .. "." .. (datein.year or "") .. " выходит за пределы разрешённого диапазона")
end
return jd
end
local function jd2jul( jd )
if type(jd) ~= "number" then return error("Промежуточная переменная " .. (jd or "") .. " не является числом") end
-- calendar date calculation
local c = jd + 32082
local d = math.floor((4*c + 3)/1461)
local e = c - math.floor(1461*d/4)
local m = math.floor((5*e + 2)/153)
local year_out = d - 4800 + math.floor(m/10)
local month_out = m + 3 - 12*math.floor(m/10)
local day_out = e - math.floor((153*m + 2)/5) + 1
-- output
local dateout = {["year"]=year_out, ["month"]=month_out, ["day"]=day_out}
return dateout
end
local function jul2jd( datein )
if not isdate(datein,true) then return error((datein.day or "") .. "." .. (datein.month or "") ..".".. (datein.year or "") .. " неподходящая дата") end
local year = datein.year
local month = datein.month
local day = datein.day
-- jd calculation
local a = math.floor((14 - month)/12)
local y = year + 4800 - a
local m = month + 12*a - 3
local offset = math.floor(y/4) - 32083
local jd = day + math.floor((153*m + 2)/5) + 365*y + offset
-- jd validation
local low, high = -1930999.5, 5373484.49999
if not (low <= jd and jd <= high) then
return error((datein.day or "") .. "." .. (datein.month or "") .."." .. (datein.year or "") .. " выходит за пределы разрешённого диапазона")
end
return jd
end
local function jd2gri( jd )
if type(jd) ~= "number" then return error("Промежуточная переменная " .. (jd or "") .. " не является числом") end
-- calendar date calculation
local a = jd + 32044
local b = math.floor((4*a + 3) / 146097)
local c = a - math.floor(146097*b/4)
local d = math.floor((4*c+3)/1461)
local e = c - math.floor(1461*d/4)
local m = math.floor((5*e+2)/153)
local day_out = e - math.floor((153*m+2)/5)+1
local month_out = m + 3 - 12*math.floor(m/10)
local year_out = 100*b + d - 4800 + math.floor(m/10)
-- output
local dateout = {["year"]=year_out, ["month"]=month_out, ["day"]=day_out}
return dateout
end
local function astroyear(num, bc)
if not num then return error()
elseif type(num) ~= "number" then return error()
end
if num < 1 then return num end
if not bc then return num
else return 1 - num
end
end
local function recalc(datein,calend)
if inlist(calend,params[1]) then
return jd2jul(gri2jd(datein)), datein
elseif inlist(calend,params[2]) then
return datein, jd2gri(jul2jd(datein))
else error("Параметр " .. (calend or "") .. " не опознан, разрешённые: " .. tCon(params[1]," ") .. " и " .. tCon(params[2]," "))
end
end
-- 50) Функции для обработки UTC
local function utc(str,margin)
local d = 1
local dchar = "+"
local beginning = "[[UTC"
local ending = "]]"
local cat = ""
local nums = {}
local hmarg, timedec = 0, 0
local mmarg = "00"
local output = ""
-- checking type of input
if not margin then margin = 0
elseif type(tonumber(margin)) ~= 'number' then
output = "Can't shift by " .. margin
error(output)
end
if type(str) ~= 'string' then
error("Нет входящей строки")
elseif str:byte(1) == 43 then
elseif inbord(str:byte(1),48,57) then cat = "[[Категория:Википедия:Ошибка в часовом поясе НП]]"
elseif str:byte(1) == 45 or string.sub(str,1,3) == "−" or string.sub(str,1,1)=="-" then d = -1
else
error(string.char(str:byte(1)) .. " недопустимый первый символ")
end
-- parsing input
for num in string.gmatch(str,"(%d+)") do
table.insert(nums,purif(num))
end
if #nums > 2 then error("Ожидается всего 2 числа, а не " .. #nums)
elseif #nums == 0 then error("Необходимо что-то ввести")
elseif #nums == 1 then
if inbord(nums[1],0,14) then timedec = d*nums[1] + margin
else error("Только часы от -14 до 14") end
elseif #nums == 2 then
if not inbord(nums[1],0,14) then error("Только часы от -14 до 14")
elseif not inbord(nums[2],0,59) then error("Минуты только от 0 до 59")
else
timedec = d*(nums[1] + nums[2]/60) + margin
end
end
if tonumber(timedec) == purif(timedec) then hmarg = timedec
else
local h, m = math.modf(math.abs(timedec))
hmarg = h
mmarg = math.floor(m*60)
end
if timedec == 0 then
dchar = "±"
elseif timedec > 0 then
elseif timedec < 0 then
dchar = "−"
end
-- output
output = beginning .. dchar .. math.abs(hmarg) .. ":" .. string.format("%02d",mmarg) .. ending .. cat
return output
end
-- 60) Блок функций ввода-вывода
function p.NthDay( frame )
local args = getArgs(frame, { frameOnly = true })
local num, wday, mont, yea, format =
purif(args[1]), purif(args[2]), purif(args[3]), purif(args[4]), args[5]
if not format then format = "%d.%m.%y" end
if not inbord(num,-5,5) then
return error("The number must be between -5 and 5")
elseif num == 0 then
return error("The number must not be zero") end
if not inbord(wday,0,6) then
return error("The day of the week must be between 0 and 6") end
if not inbord(mont,1,12) then
return error("The month must be between 1 and 12") end
if not inbord(yea,0,9999) then
return error("Wrong year number") end
if inbord(num,1,5) then
local m_start = os.time{year=yea, month=mont, day=1, hour=0}
local m_wds = tonumber(os.date("%w", m_start))
local start_shift = (
(num - bool_to_number[wday >= m_wds]) * 7
- (m_wds - wday)
) * 24 * 60 * 60
local tim = m_start + start_shift
if tonumber(os.date("%m", tim)) == mont then
return (os.date(format, tim))
else
return (err)
end
elseif inbord(num,-5,-1) then
local m_end = os.time{year = yea, month = mont + 1, day = 1, hour = 0} - 24 * 60 * 60
local m_wde = tonumber(os.date("%w", m_end))
local end_shift = ((math.abs(num + 1) + bool_to_number[wday > m_wde]) * 7
+ (m_wde - wday)) * 24 * 60 * 60
local tim = m_end - end_shift
if tonumber(os.date("%m", tim)) == mont then
return (os.date(format, tim))
else
return (err)
end
end
end
-- =p.ToIso(mw.getCurrentFrame():newChild{title="smth",args={"12 декабря 2020"}})
-- =p.ToIso(mw.getCurrentFrame():newChild{title="smth",args={"1.2.1602"}})
-- =p.ToIso(mw.getCurrentFrame():newChild{title="smth",args={"12.12.2021"}})
-- =p.ToIso(mw.getCurrentFrame():newChild{title="smth",args={"2021.12.12"}})
function p.ToIso( frame )
local args = getArgs(frame, { frameOnly = true })
local datein = args[1]
-- инициализация, заполнение обратных таблиц, копирование параметров
filling_months(mnlang, month_lang)
-- парсинг входящей даты по шаблону
local date = parse_date(datein)
if not (type(date.year) == 'number') then
return ("Wrong year: " .. unwarp(date))
end
if not (1 <= date.month and date.month <= 12) then
return ("Wrong month: " .. unwarp(date))
end
if not date.day or not (1 <= date.day and date.day <= month_end_day(date.month,date.year)) then
return ("Wrong day: " .. unwarp(date))
end
local timedate = os.time{year=date.year, month=date.month, day=date.day}
local date = os.date("%Y-%m-%d", timedate)
return date
end
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"12 декабря 2020"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"1.2.1602"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"декабрь 2020"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"12-2020"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"12.12.2021"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"2021.12.12"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"2021.11"}})
-- =p.BoxDate(mw.getCurrentFrame():newChild{title="smth",args={"11.2021"}})
function p.BoxDate( frame )
local args = getArgs(frame, { frameOnly = true })
local txtDateIn, strFormat = args[1], args[2]
local txtDateOut, date, status = p.bxDate(txtDateIn, strFormat, params)
if status.brk then
return error(status.errorText)
else
return txtDateOut
end
end
function p.bxDate( txtDateIn , strFormat, params ) -- к отладке
local txtDateOut, date, status = "", {}, {brk = false, errorCat = "", errorText = ""}
strFormat = strFormat or "j xg Y"
-- заглушка - таблица параметров на будущее
params = params or {}
if not txtDateIn then
status.errorText = e.no_data
status.errorCat = category.no_parameters
status.brk = true
else
-- заполнение служебных таблиц
filling_months(mnlang, month_lang)
end
if not status.brk then
-- парсинг входящей даты по шаблону
date = parse_date(txtDateIn)
-- заменить сообщения об ошибках на списочные
if not (date.year and type(date.year) == 'number') then
status.errorText = string.format(e.box_date,txtDateIn)
status.errorCat = category.incomplete_parameters
status.brk = true
end
if not inbord(date.month,1,12) then
status.errorText = string.format(e.box_date,txtDateIn)
status.errorCat = category.incomplete_parameters
status.brk = true
end
if not date.day and string.find(strFormat,"[dDjlNwzW]") then
strFormat = trim(string.gsub(string.gsub(strFormat,"xg","F"),"[dDjlNwzW]",""))
elseif not date.day then
elseif not inbord(date.day,1,month_end_day(date.month,date.year)) then
status.errorText = string.format(e.box_date,txtDateIn)
status.errorCat = category.incomplete_parameters
status.brk = true
end
end
if not status.brk then
txtDateOut = mwlang:formatDate(strFormat,tCon({date.year,date.month,date.day},"-"),true)
end
return txtDateOut, date, status
end
function p.ToDate( frame ) -- возможно неиспользуемая
local args = getArgs(frame, { frameOnly = true })
local mwlang = mw.getContentLanguage()
local datein = args[1]
local format = "j xg Y"
if not string.match(datein, "%p") then return datein
elseif not args[2] then
else format = args[2]
end
return mwlang:formatDate(format,datein,true)
end
-- =p.unitime(mw.getCurrentFrame():newChild{title="smth",args={"−1:30","1"}})
function p.unitime( frame )
local args = getArgs(frame, { frameOnly = true })
local DST = 0
if not args[2] then
else DST = 1 end
local utcin = ""
local input = args[1]
if not input then return "" end
if inlist(input:upper(),tzs_names) then
utcin = known_tzs[input:upper()]
elseif (string.sub(input:upper(),1,3) == 'UTC') and (string.len(input) < 10) then
utcin = string.sub(input,4)
else
if string.sub(input,1,1) == '['
or string.sub(input,1,1) == '{'
or string.sub(input,1,1):upper() == 'U'
or string.sub(input,1,1):upper() == 'M' then
return input
-- elseif not string.find(string.upper(string.sub(input,1,1)),"[\65-\90]") or
-- not string.find(string.upper(string.sub(input,1,1)),"[\192-\223]") then
-- return input
else utcin = input end
end
-- elseif string.sub(input,1,3) ~= "−" then utcin = input
-- or not (not input:find("[А-я]")) при наличии в строке юникода не работает
local output = ""
if DST == 0 then output = utc(utcin)
else output = utc(utcin) .. ", [[летнее время|летом]] " .. utc(utcin,DST)
end
return output
end
-- УСТАРЕЛО
-- =p.OldDate(mw.getCurrentFrame():newChild{title="smth",args={"20.02.2020","ю",["bc"]="1",["wd"]="1",["wy"]="1",["sq_brts"]="1",["yearmark"]="г."}})
function p.OldDate( frame )
local args = getArgs(frame, { frameOnly = true })
if not args[1] then return err end
local gdate, jdate = {}, {}
local strin = args[1]
local cal = args[2]:lower() or "г"
local bc = is(args["bc"])
local wd = is(args["wd"])
local wm = is(args["wm"])
local wy = is(args["wy"])
if not wd then wm = false end
local sq_brts = is(args["sq_brts"])
local yearmark = "года"
if yesno(args["yearmark"]) then
elseif yesno(args["yearmark"]) == false then yearmark = ""
else yearmark = trim(args["yearmark"]) or "года" end
-- local infocard = is(args["infocard"])
-- local catName = args["catName"] or false
local datein = numstr2date(strin)
datein.year = astroyear(datein.year, bc)
jdate, gdate = recalc(datein,cal)
return double_couple(jdate, gdate, wd, wm, wy, sq_brts, yearmark)
end
-- =p.NewDate(mw.getCurrentFrame():newChild{title="Salt",args={"2020-02-20"}})
-- =p.NewDate(mw.getCurrentFrame():newChild{title="smth",args={"20.02.2020","ю",["bc"]="1",["wd"]="1",["wy"]="1",["sq_brts"]="1",["yearmark"]="г."}})
-- =p.NewDate(mw.getCurrentFrame():newChild{title="smth",args={"20.02.2020",["bc"]="0",["wd"]="1",["wy"]="1",["sq_brts"]="0",["yearmark"]=""}})
function p.NewDate( frame )
local args = getArgs(frame, { frameOnly = true })
if not args[1] then return err end
local strin = args[1]
local year, month, day
if not not strin:match( "(-?%d%d%d%d%d)-(%d%d)-(%d%d)" ) then
year, month, day = strin:match( "(-?%d%d%d%d%d)-(%d%d)-(%d%d)" )
elseif not not strin:match( "(-?%d+)-(%d+)-(%d+)" ) then
year, month, day = strin:match( "(-?%d+)-(%d+)-(%d+)" )
elseif not not strin:match( "(%d%d)%.(%d%d)%.(-?%d%d%d%d%d)" ) then
day, month, year = strin:match( "(%d%d)%.(%d%d)%.(-?%d%d%d%d%d)" )
elseif not not strin:match( "(%d+)%.(%d+)%.(-?%d+)" ) then
day, month, year = strin:match( "(%d+)%.(%d+)%.(-?%d+)" )
end
if not year then return error(args[1] .. " не подходит под форматы yyyy-mm-dd или dd.mm.yyyy")
end
local cal = "г"
if (not args[2]) or (args[2] == "") then cal = "г"
else cal = args[2]:lower() end
local bc,wd,wm,wy,sq_brts =
is(args["bc"]),
is(args["wd"]),
is(args["wd"]) and is(args["wm"]),
is(args["wy"]),
is(args["sq_brts"])
year = astroyear(purif(year),bc)
local datein = {["year"]=purif(year), ["month"]=purif(month), ["day"]=purif(day)}
local jdate, gdate = recalc(datein,cal)
local yearmark = "года"
local ym = args["yearmark"] or ""
if yesno(ym) then
elseif yesno(ym) == false then yearmark = ""
else
if not not ym:match("(%d+)") then
error("Цифры в обозначении года: " .. ym)
else yearmark = trim(ym) or "года" end
end
return double_couple(jdate, gdate, wd, wm, wy, sq_brts, yearmark)
end
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"3","июня",nil,"21","мая"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"28 августа","","1916 года","15"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"3","июня","1900","21","мая"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"6","июня","1889 год","25","мая"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"28","ноября","1917","15"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"28 августа","nil","1916 года","15"}})
-- =p.Test(mw.getCurrentFrame():newChild{title="smth",args={"4","января","1915","22","декабря","1914 года"}})
-- {{OldStyleDate|день (НС)|месяц (НС)|год (НС)|день (СС)|месяц (СС)|год (СС)}}
function p.Test( frame )
local args = getArgs(frame, { frameOnly = true })
-- необходима проверка и замена nil на " "
--[[mw.log((args[1] or "") .. " " ..
(args[2] or "") .. " " ..
(args[3] or "") .. " " ..
(args[4] or "") .. " " ..
(args[5] or "") .. " " ..
(args[6] or "")) ]]--
local ingdate = triple_txt2date(args[1],args[2],args[3])
local injdate = triple_txt2date(args[4],args[5],args[6])
local j1date, g1date, j2date, g2date = init(4)
mw.log("ingdate-".. (undate(ingdate) or ""))
mw.log("injdate-".. (undate(injdate) or ""))
local bc,wd,wm,wy,sq_brts,ny =
is(args["bc"]),
is(args["wd"]),
is(args["wd"]) and is(args["wm"]),
is(args["wy"]),
is(args["sq_brts"]),
is(args["ny"])
-- подавление формата для локальных тестов
local wd, wm, wy = true, true, true
local yearmark = "года"
local ym = args["yearmark"] or ((mw.ustring.match((args[3] or ""),"(%a+)") or mw.ustring.match((args[6] or ""),"(%a+)")) or "")
-- mw.log("ym " .. ym)
if yesno(ym) then
elseif yesno(ym) == false then yearmark = ""
else
if not not ym:match("(%d+)") then
error("Цифры в обозначении года: " .. ym)
else yearmark = trim(ym) or "года" end
end
if isdate(ingdate) or isdate(injdate) then
if isdate(ingdate) then
j1date, g1date = recalc(ingdate,"g")
ingdate["full"] = true
end
if isdate(injdate) then
j2date, g2date = recalc(injdate,"j")
injdate["full"] = true
end
if ispartdate(ingdate) and ispartdate(injdate) then
mw.log("📏 " .. dmdist(ingdate,injdate))
mw.log("📏 " .. dmdist(j1date,g1date))
mw.log("📏 " .. dmdist(j2date,g2date))
mw.log("📏 " .. dmdist(ingdate,g1date))
mw.log("📏 " .. dmdist(injdate,j2date))
end
end
if ny then
if isyear(j1date) then
else j1date["year"] = "" end
if isyear(j2date) == nil then
else j2date["year"] = "" end
if isyear(g1date) == nil then
else g1date["year"] = "" end
if isyear(g2date) == nil then
else g2date["year"] = "" end
end
if (isdate(j1date) and isdate(g1date) and isdate(j2date) and isdate(g2date)) then
if ((j1date.year == j2date.year)
and (j1date.month == j2date.month)
and (j1date.day == j2date.day)) then
return double_couple(j1date, g1date, wd, wm, wy, sq_brts, yearmark)
else
mw.log("📏 " .. (tostring(dmdist(ingdate,injdate)) or ""))
return glue(args[1],args[2],args[3],args[4],args[5],args[6])
-- категория (предположительная разница в днях) и частичный вывод
end
elseif isdate(j1date) and isdate(g1date) then
return double_couple(j1date, g1date, wd, wm, wy, sq_brts, yearmark) -- категория плюс частичная проверка
elseif isdate(j2date) and isdate(g2date) then
return double_couple(j2date, g2date, wd, wm, wy, sq_brts, yearmark) -- категория плюс частичная проверка
elseif (ispartdate(ingdate) and ispartdate(injdate)) then
mw.log("ingdate ".. (undate(ingdate) or ""))
mw.log("injdate ".. (undate(injdate) or ""))
mw.log("j1date " .. (undate(j1date ) or ""))
mw.log("j2date " .. (undate(j2date ) or ""))
mw.log("g1date " .. (undate(g1date ) or ""))
mw.log("g2date " .. (undate(g2date ) or ""))
mw.log("📏 " .. (tostring(partdist(ingdate,injdate)) or "").. " — " .. (tostring(partdist(injdate,ingdate)) or ""))
return glue(args[1],args[2],args[3],args[4],args[5],args[6])
-- частичный или полный вывод, категория
else
mw.log("ingdate ".. (undate(ingdate) or ""))
mw.log("injdate ".. (undate(injdate) or ""))
mw.log("j1date " .. (undate(j1date ) or ""))
mw.log("j2date " .. (undate(j2date ) or ""))
mw.log("g1date " .. (undate(g1date ) or ""))
mw.log("g2date " .. (undate(g2date ) or ""))
return err .. category.incomplete_parameters
end
end
return p
a4a91f134ad3e3b246b3a6681a4ae438da766df4
Модуль:Arguments
828
8
9
2024-04-29T03:03:47Z
Genka Barboskin
2
Новая страница: «-- This module provides easy processing of arguments passed to Scribunto from -- #invoke. It is intended for use by other Lua modules, and should not be -- called from #invoke directly. local libraryUtil = require('libraryUtil') local checkType = libraryUtil.checkType local arguments = {} -- Generate four different tidyVal functions, so that we don't have to check the -- options every time we call it. local function tidyValDefault(key, val) if type(val)...»
Scribunto
text/plain
-- This module provides easy processing of arguments passed to Scribunto from
-- #invoke. It is intended for use by other Lua modules, and should not be
-- called from #invoke directly.
local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType
local arguments = {}
-- Generate four different tidyVal functions, so that we don't have to check the
-- options every time we call it.
local function tidyValDefault(key, val)
if type(val) == 'string' then
val = val:match('^%s*(.-)%s*$')
if val == '' then
return nil
else
return val
end
else
return val
end
end
local function tidyValTrimOnly(key, val)
if type(val) == 'string' then
return val:match('^%s*(.-)%s*$')
else
return val
end
end
local function tidyValRemoveBlanksOnly(key, val)
if type(val) == 'string' then
if val:find('%S') then
return val
else
return nil
end
else
return val
end
end
local function tidyValNoChange(key, val)
return val
end
local function matchesTitle(given, title)
local tp = type( given )
return (tp == 'string' or tp == 'number') and mw.title.new( given ).prefixedText == title
end
local translate_mt = { __index = function(t, k) return k end }
function arguments.getArgs(frame, options)
checkType('getArgs', 1, frame, 'table', true)
checkType('getArgs', 2, options, 'table', true)
frame = frame or {}
options = options or {}
--[[
-- Set up argument translation.
--]]
options.translate = options.translate or {}
if getmetatable(options.translate) == nil then
setmetatable(options.translate, translate_mt)
end
if options.backtranslate == nil then
options.backtranslate = {}
for k,v in pairs(options.translate) do
options.backtranslate[v] = k
end
end
if options.backtranslate and getmetatable(options.backtranslate) == nil then
setmetatable(options.backtranslate, {
__index = function(t, k)
if options.translate[k] ~= k then
return nil
else
return k
end
end
})
end
--[[
-- Get the argument tables. If we were passed a valid frame object, get the
-- frame arguments (fargs) and the parent frame arguments (pargs), depending
-- on the options set and on the parent frame's availability. If we weren't
-- passed a valid frame object, we are being called from another Lua module
-- or from the debug console, so assume that we were passed a table of args
-- directly, and assign it to a new variable (luaArgs).
--]]
local fargs, pargs, luaArgs
if type(frame.args) == 'table' and type(frame.getParent) == 'function' then
if options.wrappers then
--[[
-- The wrappers option makes Module:Arguments look up arguments in
-- either the frame argument table or the parent argument table, but
-- not both. This means that users can use either the #invoke syntax
-- or a wrapper template without the loss of performance associated
-- with looking arguments up in both the frame and the parent frame.
-- Module:Arguments will look up arguments in the parent frame
-- if it finds the parent frame's title in options.wrapper;
-- otherwise it will look up arguments in the frame object passed
-- to getArgs.
--]]
local parent = frame:getParent()
if not parent then
fargs = frame.args
else
local title = parent:getTitle():gsub('/песочница$', '')
local found = false
if matchesTitle(options.wrappers, title) then
found = true
elseif type(options.wrappers) == 'table' then
for _,v in pairs(options.wrappers) do
if matchesTitle(v, title) then
found = true
break
end
end
end
-- We test for false specifically here so that nil (the default) acts like true.
if found or options.frameOnly == false then
pargs = parent.args
end
if not found or options.parentOnly == false then
fargs = frame.args
end
end
else
-- options.wrapper isn't set, so check the other options.
if not options.parentOnly then
fargs = frame.args
end
if not options.frameOnly then
local parent = frame:getParent()
pargs = parent and parent.args or nil
end
end
if options.parentFirst then
fargs, pargs = pargs, fargs
end
else
luaArgs = frame
end
-- Set the order of precedence of the argument tables. If the variables are
-- nil, nothing will be added to the table, which is how we avoid clashes
-- between the frame/parent args and the Lua args.
local argTables = {fargs}
argTables[#argTables + 1] = pargs
argTables[#argTables + 1] = luaArgs
--[[
-- Generate the tidyVal function. If it has been specified by the user, we
-- use that; if not, we choose one of four functions depending on the
-- options chosen. This is so that we don't have to call the options table
-- every time the function is called.
--]]
local tidyVal = options.valueFunc
if tidyVal then
if type(tidyVal) ~= 'function' then
error(
"bad value assigned to option 'valueFunc'"
.. '(function expected, got '
.. type(tidyVal)
.. ')',
2
)
end
elseif options.trim ~= false then
if options.removeBlanks ~= false then
tidyVal = tidyValDefault
else
tidyVal = tidyValTrimOnly
end
else
if options.removeBlanks ~= false then
tidyVal = tidyValRemoveBlanksOnly
else
tidyVal = tidyValNoChange
end
end
--[[
-- Set up the args, metaArgs and nilArgs tables. args will be the one
-- accessed from functions, and metaArgs will hold the actual arguments. Nil
-- arguments are memoized in nilArgs, and the metatable connects all of them
-- together.
--]]
local args, metaArgs, nilArgs, metatable = {}, {}, {}, {}
setmetatable(args, metatable)
local function mergeArgs(tables)
--[[
-- Accepts multiple tables as input and merges their keys and values
-- into one table. If a value is already present it is not overwritten;
-- tables listed earlier have precedence. We are also memoizing nil
-- values, which can be overwritten if they are 's' (soft).
--]]
for _, t in ipairs(tables) do
for key, val in pairs(t) do
if metaArgs[key] == nil and nilArgs[key] ~= 'h' then
local tidiedVal = tidyVal(key, val)
if tidiedVal == nil then
nilArgs[key] = 's'
else
metaArgs[key] = tidiedVal
end
end
end
end
end
--[[
-- Define metatable behaviour. Arguments are memoized in the metaArgs table,
-- and are only fetched from the argument tables once. Fetching arguments
-- from the argument tables is the most resource-intensive step in this
-- module, so we try and avoid it where possible. For this reason, nil
-- arguments are also memoized, in the nilArgs table. Also, we keep a record
-- in the metatable of when pairs and ipairs have been called, so we do not
-- run pairs and ipairs on the argument tables more than once. We also do
-- not run ipairs on fargs and pargs if pairs has already been run, as all
-- the arguments will already have been copied over.
--]]
metatable.__index = function (t, key)
--[[
-- Fetches an argument when the args table is indexed. First we check
-- to see if the value is memoized, and if not we try and fetch it from
-- the argument tables. When we check memoization, we need to check
-- metaArgs before nilArgs, as both can be non-nil at the same time.
-- If the argument is not present in metaArgs, we also check whether
-- pairs has been run yet. If pairs has already been run, we return nil.
-- This is because all the arguments will have already been copied into
-- metaArgs by the mergeArgs function, meaning that any other arguments
-- must be nil.
--]]
if type(key) == 'string' then
key = options.translate[key]
end
local val = metaArgs[key]
if val ~= nil then
return val
elseif metatable.donePairs or nilArgs[key] then
return nil
end
for _, argTable in ipairs(argTables) do
local argTableVal = tidyVal(key, argTable[key])
if argTableVal ~= nil then
metaArgs[key] = argTableVal
return argTableVal
end
end
nilArgs[key] = 'h'
return nil
end
metatable.__newindex = function (t, key, val)
-- This function is called when a module tries to add a new value to the
-- args table, or tries to change an existing value.
if type(key) == 'string' then
key = options.translate[key]
end
if options.readOnly then
error(
'could not write to argument table key "'
.. tostring(key)
.. '"; the table is read-only',
2
)
elseif options.noOverwrite and args[key] ~= nil then
error(
'could not write to argument table key "'
.. tostring(key)
.. '"; overwriting existing arguments is not permitted',
2
)
elseif val == nil then
--[[
-- If the argument is to be overwritten with nil, we need to erase
-- the value in metaArgs, so that __index, __pairs and __ipairs do
-- not use a previous existing value, if present; and we also need
-- to memoize the nil in nilArgs, so that the value isn't looked
-- up in the argument tables if it is accessed again.
--]]
metaArgs[key] = nil
nilArgs[key] = 'h'
else
metaArgs[key] = val
end
end
local function translatenext(invariant)
local k, v = next(invariant.t, invariant.k)
invariant.k = k
if k == nil then
return nil
elseif type(k) ~= 'string' or not options.backtranslate then
return k, v
else
local backtranslate = options.backtranslate[k]
if backtranslate == nil then
-- Skip this one. This is a tail call, so this won't cause stack overflow
return translatenext(invariant)
else
return backtranslate, v
end
end
end
metatable.__pairs = function ()
-- Called when pairs is run on the args table.
if not metatable.donePairs then
mergeArgs(argTables)
metatable.donePairs = true
end
return translatenext, { t = metaArgs }
end
local function inext(t, i)
-- This uses our __index metamethod
local v = t[i + 1]
if v ~= nil then
return i + 1, v
end
end
metatable.__ipairs = function (t)
-- Called when ipairs is run on the args table.
return inext, t, 0
end
return args
end
return arguments
e6be8dfccffa2057c3d50700f350d8d140c1dbf9
Модуль:Message box/configuration
828
9
10
2024-04-29T03:04:55Z
Genka Barboskin
2
Новая страница: «-------------------------------------------------------------------------------- -- Message box configuration -- -- -- -- This module contains configuration data for [[Module:Message box]]. -- -------------------------------------------------------------------------------- return { ambox = { types = { speedy = { class...»
Scribunto
text/plain
--------------------------------------------------------------------------------
-- Message box configuration --
-- --
-- This module contains configuration data for [[Module:Message box]]. --
--------------------------------------------------------------------------------
return {
ambox = {
types = {
speedy = {
class = 'ambox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'ambox-delete',
image = 'Stop hand nuvola.svg'
},
content = {
class = 'ambox-content',
image = 'Emblem-important.svg'
},
style = {
class = 'ambox-style',
image = 'Broom_icon.svg'
},
move = {
class = 'ambox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'ambox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'ambox-notice',
image = 'Information.svg'
},
good = {
class = 'ambox-good',
image = 'Green star boxed.svg'
},
serious = {
class = 'ambox-serious',
image = 'Stop hand nuvola.svg'
},
merge = {
class = 'ambox-merge',
image = 'Merge-split-transwiki default.svg'
},
discussion = {
class = 'ambox-discussion',
image = 'Nuvola apps ksirc.png'
}
},
default = 'notice',
allowBlankParams = {'talk', 'sect', 'date', 'issue', 'fix', 'subst', 'hidden', 'image'},
allowSmall = true,
smallParam = 'left',
smallClass = 'mbox-small-left',
substCheck = true,
classes = {'metadata', 'ambox'},
imageEmptyCell = true,
imageCheckBlank = true,
imageSmallSize = '20x20px',
imageCellDiv = true,
useCollapsibleTextFields = true,
imageRightNone = true,
sectionDefault = 'статья',
allowMainspaceCategories = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для статей',
templateCategoryRequireName = true,
templateErrorCategory = 'Шаблоны:Шаблоны-сообщения для статей с пропущенными параметрами',
templateErrorParamsToCheck = {'issue', 'fix'},
removalNotice = '[[Help:Maintenance template removal|Learn how and when to remove this template message]]',
templatestyles = 'Module:Message box/ambox.css',
},
cmbox = {
types = {
speedy = {
class = 'cmbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'cmbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'cmbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'cmbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'cmbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'cmbox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'cmbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'cmbox'},
imageEmptyCell = true,
useCollapsibleTextFields = true,
templatestyles = 'Module:Message box/cmbox.css',
},
fmbox = {
types = {
warning = {
class = 'fmbox-warning',
image = 'Ambox warning pn.svg'
},
editnotice = {
class = 'fmbox-editnotice',
image = 'Information icon4.svg'
},
system = {
class = 'fmbox-system',
image = 'Information icon4.svg'
}
},
default = 'system',
showInvalidTypeError = true,
classes = {'fmbox'},
imageEmptyCell = false,
imageRightNone = false,
useCollapsibleTextFields = true,
templatestyles = 'Module:Message box/fmbox.css',
},
imbox = {
types = {
speedy = {
class = 'imbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'imbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'imbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'imbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'imbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'imbox-protection',
image = 'Padlock-silver-medium.svg'
},
license = {
class = 'imbox-license licensetpl',
image = 'Imbox license.png' -- @todo We need an SVG version of this
},
featured = {
class = 'imbox-featured',
image = 'Cscr-featured.svg'
},
notice = {
class = 'imbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'imbox'},
imageEmptyCell = true,
below = true,
useCollapsibleTextFields = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для файлов',
templatestyles = 'Module:Message box/imbox.css',
},
ombox = {
types = {
speedy = {
class = 'ombox-speedy',
image = 'OOjs UI icon alert-destructive.svg'
},
delete = {
class = 'ombox-delete',
image = 'OOjs UI icon alert-destructive.svg'
},
content = {
class = 'ombox-content',
image = 'OOjs UI icon notice-warning.svg'
},
style = {
class = 'ombox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'ombox-move',
image = 'Imbox move.png'
},
protection = {
class = 'ombox-protection',
image = 'Imbox protection.png'
},
notice = {
class = 'ombox-notice',
image = 'OOjs UI icon info-progressive.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'ombox'},
allowSmall = true,
imageEmptyCell = true,
imageRightNone = true,
useCollapsibleTextFields = true,
templatestyles = 'Module:Message box/ombox.css',
},
tmbox = {
types = {
speedy = {
class = 'tmbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'tmbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'tmbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'tmbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'tmbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'tmbox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'tmbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'tmbox'},
allowSmall = true,
imageRightNone = true,
imageEmptyCell = true,
imageEmptyCellStyle = true,
useCollapsibleTextFields = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для страниц обсуждений',
templatestyles = 'Module:Message box/tmbox.css',
}
}
2c0750ec1561e8ec25c0988c411f3c69e4957483
18
10
2024-04-29T03:19:01Z
Genka Barboskin
2
Scribunto
text/plain
--------------------------------------------------------------------------------
-- Message box configuration --
-- --
-- This module contains configuration data for [[Module:Message box]]. --
--------------------------------------------------------------------------------
return {
ambox = {
types = {
speedy = {
class = 'ambox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'ambox-delete',
image = 'Stop hand nuvola.svg'
},
content = {
class = 'ambox-content',
image = 'Emblem-important.svg'
},
style = {
class = 'ambox-style',
image = 'Broom_icon.svg'
},
move = {
class = 'ambox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'ambox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'ambox-notice',
image = 'Information.svg'
},
good = {
class = 'ambox-good',
image = 'Green star boxed.svg'
},
serious = {
class = 'ambox-serious',
image = 'Stop hand nuvola.svg'
},
merge = {
class = 'ambox-merge',
image = 'Merge-split-transwiki default.svg'
},
discussion = {
class = 'ambox-discussion',
image = 'Nuvola apps ksirc.png'
}
},
default = 'notice',
allowBlankParams = {'talk', 'sect', 'date', 'issue', 'fix', 'subst', 'hidden', 'image'},
allowSmall = true,
smallParam = 'left',
smallClass = 'mbox-small-left',
substCheck = true,
classes = {'metadata', 'ambox'},
imageEmptyCell = true,
imageCheckBlank = true,
imageSmallSize = '20x20px',
imageCellDiv = true,
useCollapsibleTextFields = true,
imageRightNone = true,
sectionDefault = 'статья',
allowMainspaceCategories = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для статей',
templateCategoryRequireName = true,
templateErrorCategory = 'Шаблоны:Шаблоны-сообщения для статей с пропущенными параметрами',
templateErrorParamsToCheck = {'issue', 'fix'},
removalNotice = '[[Help:Maintenance template removal|Learn how and when to remove this template message]]',
},
cmbox = {
types = {
speedy = {
class = 'cmbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'cmbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'cmbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'cmbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'cmbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'cmbox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'cmbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'cmbox'},
imageEmptyCell = true,
useCollapsibleTextFields = true,
},
fmbox = {
types = {
warning = {
class = 'fmbox-warning',
image = 'Ambox warning pn.svg'
},
editnotice = {
class = 'fmbox-editnotice',
image = 'Information icon4.svg'
},
system = {
class = 'fmbox-system',
image = 'Information icon4.svg'
}
},
default = 'system',
showInvalidTypeError = true,
classes = {'fmbox'},
imageEmptyCell = false,
imageRightNone = false,
useCollapsibleTextFields = true,
},
imbox = {
types = {
speedy = {
class = 'imbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'imbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'imbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'imbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'imbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'imbox-protection',
image = 'Padlock-silver-medium.svg'
},
license = {
class = 'imbox-license licensetpl',
image = 'Imbox license.png' -- @todo We need an SVG version of this
},
featured = {
class = 'imbox-featured',
image = 'Cscr-featured.svg'
},
notice = {
class = 'imbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'imbox'},
imageEmptyCell = true,
below = true,
useCollapsibleTextFields = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для файлов',
},
ombox = {
types = {
speedy = {
class = 'ombox-speedy',
image = 'OOjs UI icon alert-destructive.svg'
},
delete = {
class = 'ombox-delete',
image = 'OOjs UI icon alert-destructive.svg'
},
content = {
class = 'ombox-content',
image = 'OOjs UI icon notice-warning.svg'
},
style = {
class = 'ombox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'ombox-move',
image = 'Imbox move.png'
},
protection = {
class = 'ombox-protection',
image = 'Imbox protection.png'
},
notice = {
class = 'ombox-notice',
image = 'OOjs UI icon info-progressive.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'ombox'},
allowSmall = true,
imageEmptyCell = true,
imageRightNone = true,
useCollapsibleTextFields = true,
},
tmbox = {
types = {
speedy = {
class = 'tmbox-speedy',
image = 'Ambox warning pn.svg'
},
delete = {
class = 'tmbox-delete',
image = 'Ambox warning pn.svg'
},
content = {
class = 'tmbox-content',
image = 'Ambox important.svg'
},
style = {
class = 'tmbox-style',
image = 'Edit-clear.svg'
},
move = {
class = 'tmbox-move',
image = 'Merge-split-transwiki default.svg'
},
protection = {
class = 'tmbox-protection',
image = 'Padlock-silver-medium.svg'
},
notice = {
class = 'tmbox-notice',
image = 'Information icon4.svg'
}
},
default = 'notice',
showInvalidTypeError = true,
classes = {'tmbox'},
allowSmall = true,
imageRightNone = true,
imageEmptyCell = true,
imageEmptyCellStyle = true,
useCollapsibleTextFields = true,
templateCategory = 'Шаблоны:Шаблоны-сообщения для страниц обсуждений',
}
}
3ae77df2f28bd40a4c0a10378d6653325d41ee08
Модуль:Category handler/data
828
10
11
2024-04-29T03:06:16Z
Genka Barboskin
2
Новая страница: «-- This module assembles data to be passed to [[Module:Category handler]] using -- mw.loadData. This includes the configuration data and whether the current -- page matches the title blacklist. local data = require('Module:Category handler/config') local mShared = require('Module:Category handler/shared') local blacklist = require('Module:Category handler/blacklist') local title = mw.title.getCurrentTitle() data.currentTitleMatchesBlacklist = mShared.match...»
Scribunto
text/plain
-- This module assembles data to be passed to [[Module:Category handler]] using
-- mw.loadData. This includes the configuration data and whether the current
-- page matches the title blacklist.
local data = require('Module:Category handler/config')
local mShared = require('Module:Category handler/shared')
local blacklist = require('Module:Category handler/blacklist')
local title = mw.title.getCurrentTitle()
data.currentTitleMatchesBlacklist = mShared.matchesBlacklist(
title.prefixedText,
blacklist
)
data.currentTitleNamespaceParameters = mShared.getNamespaceParameters(
title,
mShared.getParamMappings()
)
return data
abbc68048ff698e88dda06b64ecf384bbf583120
Модуль:Category handler/config
828
11
12
2024-04-29T03:07:17Z
Genka Barboskin
2
Новая страница: «-------------------------------------------------------------------------------- -- [[Module:Category handler]] configuration data -- -- Language-specific parameter names and values can be set here. -- -- For blacklist config, see [[Module:Category handler/blacklist]]. -- -------------------------------------------------------------------------------- local cfg = {} -- Don't edit this line. ---------------...»
Scribunto
text/plain
--------------------------------------------------------------------------------
-- [[Module:Category handler]] configuration data --
-- Language-specific parameter names and values can be set here. --
-- For blacklist config, see [[Module:Category handler/blacklist]]. --
--------------------------------------------------------------------------------
local cfg = {} -- Don't edit this line.
--------------------------------------------------------------------------------
-- Start configuration data --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Parameter names --
-- These configuration items specify custom parameter names. --
-- To add one extra name, you can use this format: --
-- --
-- foo = 'parameter name', --
-- --
-- To add multiple names, you can use this format: --
-- --
-- foo = {'parameter name 1', 'parameter name 2', 'parameter name 3'}, --
--------------------------------------------------------------------------------
cfg.parameters = {
-- The nocat and categories parameter suppress
-- categorisation. They are used with Module:Yesno, and work as follows:
--
-- cfg.nocat:
-- Result of yesno() Effect
-- true Categorisation is suppressed
-- false Categorisation is allowed, and
-- the blacklist check is skipped
-- nil Categorisation is allowed
--
-- cfg.categories:
-- Result of yesno() Effect
-- true Categorisation is allowed, and
-- the blacklist check is skipped
-- false Categorisation is suppressed
-- nil Categorisation is allowed
nocat = 'nocat',
categories = 'categories',
-- The parameter name for the legacy "category2" parameter. This skips the
-- blacklist if set to the cfg.category2Yes value, and suppresses
-- categorisation if present but equal to anything other than
-- cfg.category2Yes or cfg.category2Negative.
category2 = 'category2',
-- cfg.subpage is the parameter name to specify how to behave on subpages.
subpage = 'subpage',
-- The parameter for data to return in all namespaces.
all = 'all',
-- The parameter name for data to return if no data is specified for the
-- namespace that is detected.
other = 'other',
-- The parameter name used to specify a page other than the current page;
-- used for testing and demonstration.
demopage = 'page',
}
--------------------------------------------------------------------------------
-- Parameter values --
-- These are set values that can be used with certain parameters. Only one --
-- value can be specified, like this: --
-- --
-- cfg.foo = 'value name' -- --
--------------------------------------------------------------------------------
-- The following settings are used with the cfg.category2 parameter. Setting
-- cfg.category2 to cfg.category2Yes skips the blacklist, and if cfg.category2
-- is present but equal to anything other than cfg.category2Yes or
-- cfg.category2Negative then it supresses cateogrisation.
cfg.category2Yes = 'yes'
cfg.category2Negative = '¬'
-- The following settings are used with the cfg.subpage parameter.
-- cfg.subpageNo is the value to specify to not categorise on subpages;
-- cfg.subpageOnly is the value to specify to only categorise on subpages.
cfg.subpageNo = 'no'
cfg.subpageOnly = 'only'
--------------------------------------------------------------------------------
-- Default namespaces --
-- This is a table of namespaces to categorise by default. The keys are the --
-- namespace numbers. --
--------------------------------------------------------------------------------
cfg.defaultNamespaces = {
[ 0] = true, -- main
[ 6] = true, -- file
[ 12] = true, -- help
[ 14] = true, -- category
[100] = true, -- portal
[108] = true, -- book
}
--------------------------------------------------------------------------------
-- Wrappers --
-- This is a wrapper template or a list of wrapper templates to be passed to --
-- [[Module:Arguments]]. --
--------------------------------------------------------------------------------
cfg.wrappers = 'Template:Category handler'
--------------------------------------------------------------------------------
-- End configuration data --
--------------------------------------------------------------------------------
return cfg -- Don't edit this line.
373cd107b13a5b00e6a1b7e66a749f12502c849d
Модуль:Category handler/shared
828
12
13
2024-04-29T03:07:53Z
Genka Barboskin
2
Новая страница: «-- This module contains shared functions used by [[Module:Category handler]] -- and its submodules. local p = {} function p.matchesBlacklist(page, blacklist) for i, pattern in ipairs(blacklist) do local match = mw.ustring.match(page, pattern) if match then return true end end return false end function p.getParamMappings(useLoadData) local dataPage = 'Module:Namespace detect/data' if useLoadData then return mw.loadData(dataPage).mappings e...»
Scribunto
text/plain
-- This module contains shared functions used by [[Module:Category handler]]
-- and its submodules.
local p = {}
function p.matchesBlacklist(page, blacklist)
for i, pattern in ipairs(blacklist) do
local match = mw.ustring.match(page, pattern)
if match then
return true
end
end
return false
end
function p.getParamMappings(useLoadData)
local dataPage = 'Module:Namespace detect/data'
if useLoadData then
return mw.loadData(dataPage).mappings
else
return require(dataPage).mappings
end
end
function p.getNamespaceParameters(titleObj, mappings)
-- We don't use title.nsText for the namespace name because it adds
-- underscores.
local mappingsKey
if titleObj.isTalkPage then
mappingsKey = 'talk'
else
mappingsKey = mw.site.namespaces[titleObj.namespace].name
end
mappingsKey = mw.ustring.lower(mappingsKey)
return mappings[mappingsKey] or {}
end
return p
d2d5de1a031e6ce97c242cbfa8afe7a92cb9eca5
Модуль:Category handler/blacklist
828
13
14
2024-04-29T03:08:20Z
Genka Barboskin
2
Новая страница: «-- This module contains the blacklist used by [[Module:Category handler]]. -- Pages that match Lua patterns in this list will not be categorised unless -- categorisation is explicitly requested. return { '^Main Page$', -- don't categorise the main page. -- Don't categorise the following pages or their subpages. -- "%f[/\0]" matches if the next character is "/" or the end of the string. '^Wikipedia:Cascade%-protected items%f[/\0]', '^Us...»
Scribunto
text/plain
-- This module contains the blacklist used by [[Module:Category handler]].
-- Pages that match Lua patterns in this list will not be categorised unless
-- categorisation is explicitly requested.
return {
'^Main Page$', -- don't categorise the main page.
-- Don't categorise the following pages or their subpages.
-- "%f[/\0]" matches if the next character is "/" or the end of the string.
'^Wikipedia:Cascade%-protected items%f[/\0]',
'^User:UBX%f[/\0]', -- The userbox "template" space.
'^User talk:UBX%f[/\0]',
-- Don't categorise subpages of these pages, but allow
-- categorisation of the base page.
'^Wikipedia:Template messages/.*$',
'/[aA]rchive' -- Don't categorise archives.
}
c84948ad9808d5d323408d5d10d5652f748a0550
Модуль:Namespace detect/data
828
14
15
2024-04-29T03:09:35Z
Genka Barboskin
2
Новая страница: «-------------------------------------------------------------------------------- -- Namespace detect data -- -- This module holds data for [[Module:Namespace detect]] to be loaded per -- -- page, rather than per #invoke, for performance reasons. -- -------------------------------------------------------------------------------- local cfg = require('Module:Namespace detect/config') l...»
Scribunto
text/plain
--------------------------------------------------------------------------------
-- Namespace detect data --
-- This module holds data for [[Module:Namespace detect]] to be loaded per --
-- page, rather than per #invoke, for performance reasons. --
--------------------------------------------------------------------------------
local cfg = require('Module:Namespace detect/config')
local function addKey(t, key, defaultKey)
if key ~= defaultKey then
t[#t + 1] = key
end
end
-- Get a table of parameters to query for each default parameter name.
-- This allows wikis to customise parameter names in the cfg table while
-- ensuring that default parameter names will always work. The cfg table
-- values can be added as a string, or as an array of strings.
local defaultKeys = {
'main',
'talk',
'other',
'subjectns',
'demospace',
'demopage'
}
local argKeys = {}
for i, defaultKey in ipairs(defaultKeys) do
argKeys[defaultKey] = {defaultKey}
end
for defaultKey, t in pairs(argKeys) do
local cfgValue = cfg[defaultKey]
local cfgValueType = type(cfgValue)
if cfgValueType == 'string' then
addKey(t, cfgValue, defaultKey)
elseif cfgValueType == 'table' then
for i, key in ipairs(cfgValue) do
addKey(t, key, defaultKey)
end
end
cfg[defaultKey] = nil -- Free the cfg value as we don't need it any more.
end
local function getParamMappings()
--[[
-- Returns a table of how parameter names map to namespace names. The keys
-- are the actual namespace names, in lower case, and the values are the
-- possible parameter names for that namespace, also in lower case. The
-- table entries are structured like this:
-- {
-- [''] = {'main'},
-- ['wikipedia'] = {'wikipedia', 'project', 'wp'},
-- ...
-- }
--]]
local mappings = {}
local mainNsName = mw.site.subjectNamespaces[0].name
mainNsName = mw.ustring.lower(mainNsName)
mappings[mainNsName] = mw.clone(argKeys.main)
mappings['talk'] = mw.clone(argKeys.talk)
for nsid, ns in pairs(mw.site.subjectNamespaces) do
if nsid ~= 0 then -- Exclude main namespace.
local nsname = mw.ustring.lower(ns.name)
local canonicalName = mw.ustring.lower(ns.canonicalName)
mappings[nsname] = {nsname}
if canonicalName ~= nsname then
table.insert(mappings[nsname], canonicalName)
end
for _, alias in ipairs(ns.aliases) do
table.insert(mappings[nsname], mw.ustring.lower(alias))
end
end
end
return mappings
end
return {
argKeys = argKeys,
cfg = cfg,
mappings = getParamMappings()
}
d224f42a258bc308ef3ad8cc8686cd7a4f47d005
Модуль:Namespace detect/config
828
15
16
2024-04-29T03:10:34Z
Genka Barboskin
2
Новая страница: «-------------------------------------------------------------------------------- -- Namespace detect configuration data -- -- -- -- This module stores configuration data for Module:Namespace detect. Here -- -- you can localise the module to your wiki's language. -- --...»
Scribunto
text/plain
--------------------------------------------------------------------------------
-- Namespace detect configuration data --
-- --
-- This module stores configuration data for Module:Namespace detect. Here --
-- you can localise the module to your wiki's language. --
-- --
-- To activate a configuration item, you need to uncomment it. This means --
-- that you need to remove the text "-- " at the start of the line. --
--------------------------------------------------------------------------------
local cfg = {} -- Don't edit this line.
--------------------------------------------------------------------------------
-- Parameter names --
-- These configuration items specify custom parameter names. Values added --
-- here will work in addition to the default English parameter names. --
-- To add one extra name, you can use this format: --
-- --
-- cfg.foo = 'parameter name' --
-- --
-- To add multiple names, you can use this format: --
-- --
-- cfg.foo = {'parameter name 1', 'parameter name 2', 'parameter name 3'} --
--------------------------------------------------------------------------------
---- This parameter displays content for the main namespace:
-- cfg.main = 'main'
---- This parameter displays in talk namespaces:
-- cfg.talk = 'talk'
---- This parameter displays content for "other" namespaces (namespaces for which
---- parameters have not been specified):
-- cfg.other = 'other'
---- This parameter makes talk pages behave as though they are the corresponding
---- subject namespace. Note that this parameter is used with [[Module:Yesno]].
---- Edit that module to change the default values of "yes", "no", etc.
-- cfg.subjectns = 'subjectns'
---- This parameter sets a demonstration namespace:
-- cfg.demospace = 'demospace'
---- This parameter sets a specific page to compare:
cfg.demopage = 'page'
--------------------------------------------------------------------------------
-- Table configuration --
-- These configuration items allow customisation of the "table" function, --
-- used to generate a table of possible parameters in the module --
-- documentation. --
--------------------------------------------------------------------------------
---- The header for the namespace column in the wikitable containing the list of
---- possible subject-space parameters.
-- cfg.wikitableNamespaceHeader = 'Namespace'
---- The header for the wikitable containing the list of possible subject-space
---- parameters.
-- cfg.wikitableAliasesHeader = 'Aliases'
--------------------------------------------------------------------------------
-- End of configuration data --
--------------------------------------------------------------------------------
return cfg -- Don't edit this line.
0e4ff08d13c4b664d66b32c232deb129b77c1a56
Шаблон:Удалить
10
16
20
2024-04-29T03:20:28Z
Genka Barboskin
2
Новая страница: «{{safesubst:<noinclude />ifsubst| <<includeonly />noinclude> }}{{safesubst:<noinclude />#invoke:Unsubst||$format=Y-m-d|1=__DATE__|$B= {{ambox | name = {{{name|К удалению}}} | type = speedy | id = request_for_deletion | image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]] | text = '''{{#switch: ~{{NAMESPACE}} | ~Файл = Этот файл | ~Шаблон = Этот шаблон | ~Кат...»
wikitext
text/x-wiki
{{safesubst:<noinclude />ifsubst| <<includeonly />noinclude> }}{{safesubst:<noinclude />#invoke:Unsubst||$format=Y-m-d|1=__DATE__|$B=
{{ambox
| name = {{{name|К удалению}}}
| type = speedy
| id = request_for_deletion
| image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]]
| text = '''{{#switch: ~{{NAMESPACE}}
| ~Файл = Этот файл
| ~Шаблон = Этот шаблон
| ~Категория = Эту категорию
| ~Участник = Эту страницу участника
| ~ = Эту статью
| Эту страницу
}} - кандидат на удаление.'''
| text-small = {{#if: {{{1|}}}
| Пояснение причин и соответствующее обсуждение вы можете найти на странице {{nobr|[[Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}#{{#if: {{{2|}}}
| {{{2}}}
| {{FULLPAGENAME}}
}}{{!}}Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}]]}}.
| <span class="error">Не указана страница, на которой происходит обсуждение.</span><includeonly>[[Категория:Википедия:Страницы с номинациями, местоположение которых не указано|У]]</includeonly>
}}<br>Пока процесс обсуждения не завершён, {{#if: {{NAMESPACE}}
| страницу
| статью
}} можно попытаться улучшить, однако следует воздерживаться от переименований или немотивированного удаления содержания, подробнее см. [[Википедия:Что делать, если ваша статья стала кандидатом на удаление|руководство к дальнейшему действию]].<br>Не снимайте пометку о выставлении на удаление до [[ВП:ППИ|подведения итога]] обсуждения.
<hr {{#ifeq: {{NAMESPACE}}
| {{ns:14}}
| class="group-closer-show group-sysop-show"
}}>
{{#ifeq: {{{1}}}
| {{#time: Y-m-d}}
| ''Номинатору: [{{fullurl:Википедия:К удалению/{{#time: j xg Y | {{{1}}} }}|action=edit§ion=new&preview=no&preloadtitle=%5B%5B{{#switch: {{NAMESPACE}}
| {{ns:6}} | {{ns:14}} = %3A
}}{{urlencode:{{FULLPAGENAME}}}}%5D%5D&editintro=template:editintro/КУ}} добавить секцию обсуждения]''.<br>
}}<!--
-->{{Администраторам|согласно [[Категория:К удалению{{#if: {{{1}}}
| /{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}
}}#{{FULLPAGENAME}}]]}}
}}<includeonly>{{#if: {{{nocat|}}}
|
| {{Сортировка: КУ}}[[Категория::Кандидаты на удаление]][[Категория:Кандидаты на удаление по дате номинации|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]]{{#ifeq: {{Просроченные подведения итогов|{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}}}
| true
| [[Категория:Википедия:Просроченные подведения итогов по удалению страниц|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]][[Категория:Википедия:Просроченные подведения итогов по удалению страниц по алфавиту|{{FULLPAGENAME}}]]
}}{{#switch: ~{{NAMESPACE}}
| ~Файл = [[Категория:Файлы:К удалению]]
}}
}}</includeonly>
}}{{safesubst:<noinclude />ifsubst| </<includeonly />noinclude> }}<noinclude>
{{doc}}
</noinclude>
b082e454629aa7e21000c339ee3e4761c588f1b6
29
20
2024-04-29T03:34:34Z
Genka Barboskin
2
wikitext
text/x-wiki
{{safesubst:<noinclude />ifsubst| <<includeonly />noinclude> }}{{safesubst:<noinclude />#invoke:Unsubst||$format=Y-m-d|1=__DATE__|$B=
{{ambox
| name = {{{name|К удалению}}}
| type = speedy
| id = request_for_deletion
| image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]]
| text = '''{{#switch: ~{{NAMESPACE}}
| ~Файл = Этот файл
| ~Шаблон = Этот шаблон
| ~Категория = Эту категорию
| ~Участник = Эту страницу участника
| ~ = Эту статью
| Эту страницу
}} - кандидат на удаление.'''
| text-small = {{#if: {{{1|}}}
| Пояснение причин и соответствующее обсуждение вы можете найти на странице {{nobr|[[Монетопедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}#{{#if: {{{2|}}}
| {{{2}}}
| {{FULLPAGENAME}}
}}{{!}}Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}]]}}.
| <span class="error">Не указана страница, на которой происходит обсуждение.</span><includeonly>[[Категория:Страницы с номинациями, местоположение которых не указано|У]]</includeonly>
}}<br>Пока процесс обсуждения не завершён, {{#if: {{NAMESPACE}}
| страницу
| статью
}} на исправление статьи даётся 3 дня, если в течении срока статья не будет исправлена, то она будет удалена.
<hr {{#ifeq: {{NAMESPACE}}
| {{ns:14}}
| class="group-closer-show group-sysop-show"
}}>
{{#ifeq: {{{1}}}
| {{#time: Y-m-d}}
| ''Номинатору: [{{fullurl:Монетопедия:К удалению/{{#time: j xg Y | {{{1}}} }}|action=edit§ion=new&preview=no&preloadtitle=%5B%5B{{#switch: {{NAMESPACE}}
| {{ns:6}} | {{ns:14}} = %3A
}}{{urlencode:{{FULLPAGENAME}}}}%5D%5D&editintro=template:editintro/КУ}} добавить секцию обсуждения]''.<br>
}}<!--
-->{{Администраторам|согласно [[Категория:К удалению{{#if: {{{1}}}
| /{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}
}}#{{FULLPAGENAME}}]]}}
}}<includeonly>{{#if: {{{nocat|}}}
|
| {{Сортировка: КУ}}[[Категория:Кандидаты на удаление]][[Категория:Кандидаты на удаление по дате номинации|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]]{{#ifeq: {{Просроченные подведения итогов|{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}}}
| true
| [[Категория:Просроченные подведения итогов по удалению страниц|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]][[Категория:Просроченные подведения итогов по удалению страниц по алфавиту|{{FULLPAGENAME}}]]
}}{{#switch: ~{{NAMESPACE}}
| ~Файл = [[Категория:Файлы К удалению]]
}}
}}</includeonly>
}}{{safesubst:<noinclude />ifsubst| </<includeonly />noinclude> }}<noinclude>
{{doc}}
</noinclude>
f4722f9c25b37d49b907926a2e505d893e65f16e
32
29
2024-04-29T03:37:31Z
Genka Barboskin
2
wikitext
text/x-wiki
{{safesubst:<noinclude />ifsubst| <<includeonly />noinclude> }}{{safesubst:<noinclude />#invoke:Unsubst||$format=Y-m-d|1=__DATE__|$B=
{{ambox
| name = {{{name|К удалению}}}
| type = speedy
| id = request_for_deletion
| image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]]
| text = '''{{#switch: ~{{NAMESPACE}}
| ~Файл = Этот файл
| ~Шаблон = Этот шаблон
| ~Категория = Эту категорию
| ~Участник = Эту страницу участника
| ~ = Эту статью
| Эту страницу
}} - кандидат на удаление.'''
| text-small = {{#if: {{{1|}}}
| Пояснение причин и соответствующее обсуждение вы можете найти на странице {{nobr|[[Монетопедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}#{{#if: {{{2|}}}
| {{{2}}}
| {{FULLPAGENAME}}
}}{{!}}Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}]]}}.
| <span class="error">Не указана страница, на которой происходит обсуждение.</span><includeonly>[[Категория:Страницы с номинациями, местоположение которых не указано|У]]</includeonly>
}}<br>Пока процесс обсуждения не завершён, {{#if: {{NAMESPACE}}
| страницу
| статью
}} на исправление статьи даётся 3 дня, если в течении срока статья не будет исправлена, то она будет удалена.
<hr {{#ifeq: {{NAMESPACE}}
| {{ns:14}}
| class="group-closer-show group-sysop-show"
}}>
{{#ifeq: {{{1}}}
| {{#time: Y-m-d}}
| ''Номинатору: [{{fullurl:Монетопедия:К удалению/{{#time: j xg Y | {{{1}}} }}|action=edit§ion=new&preview=no&preloadtitle=%5B%5B{{#switch: {{NAMESPACE}}
| {{ns:6}} | {{ns:14}} = %3A
}}{{urlencode:{{FULLPAGENAME}}}}%5D%5D&editintro=template:editintro/КУ}} добавить секцию обсуждения]''.<br>
}}
| {{Сортировка: КУ}}[[Категория:Кандидаты на удаление]][[Категория:Кандидаты на удаление по дате номинации|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]]{{#ifeq: {{Просроченные подведения итогов|{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}}}
| true
| [[Категория:Просроченные подведения итогов по удалению страниц|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]][[Категория:Просроченные подведения итогов по удалению страниц по алфавиту|{{FULLPAGENAME}}]]
}}{{#switch: ~{{NAMESPACE}}
| ~Файл = [[Категория:Файлы К удалению]]
}}
}}</includeonly>
}}{{safesubst:<noinclude />ifsubst| </<includeonly />noinclude> }}<noinclude>
{{doc}}
</noinclude>
9b299939ecdc634f4096353d1d9a18c74f0ff155
33
32
2024-04-29T09:25:59Z
Genka Barboskin
2
wikitext
text/x-wiki
{{ambox
| name = {{{name|К удалению}}}
| type = speedy
| id = request_for_deletion
| image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]]
| text = '''{{#switch: ~{{NAMESPACE}}
| ~Файл = Этот файл
| ~Шаблон = Этот шаблон
| ~Категория = Эту категорию
| ~Участник = Эту страницу участника
| ~ = Эту статью
| Эту страницу
}} - кандидат на удаление.'''
| text-small = {{#if: {{{1|}}}
| Пояснение причин и соответствующее обсуждение вы можете найти на странице {{nobr|[[Монетопедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}#{{#if: {{{2|}}}
| {{{2}}}
| {{FULLPAGENAME}}
}}{{!}}Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}]]}}.
| <span class="error">Не указана страница, на которой происходит обсуждение.</span><includeonly>[[Категория:Страницы с номинациями, местоположение которых не указано|У]]</includeonly>
}}<br>Пока процесс обсуждения не завершён, {{#if: {{NAMESPACE}}
| страницу
| статью
}} на исправление статьи даётся 3 дня, если в течении срока статья не будет исправлена, то она будет удалена.
<hr {{#ifeq: {{NAMESPACE}}
| {{ns:14}}
| class="group-closer-show group-sysop-show"
}}>
{{#ifeq: {{{1}}}
| {{#time: Y-m-d}}
| ''Номинатору: [{{fullurl:Монетопедия:К удалению/{{#time: j xg Y | {{{1}}} }}|action=edit§ion=new&preview=no&preloadtitle=%5B%5B{{#switch: {{NAMESPACE}}
| {{ns:6}} | {{ns:14}} = %3A
}}{{urlencode:{{FULLPAGENAME}}}}%5D%5D&editintro=template:editintro/КУ}} добавить секцию обсуждения]''.<br>
}}
| {{Сортировка: КУ}}[[Категория:Кандидаты на удаление]][[Категория:Кандидаты на удаление по дате номинации|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]]{{#ifeq: {{Просроченные подведения итогов|{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}}}
| true
| [[Категория:Просроченные подведения итогов по удалению страниц|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]][[Категория:Просроченные подведения итогов по удалению страниц по алфавиту|{{FULLPAGENAME}}]]
}}{{#switch: ~{{NAMESPACE}}
| ~Файл = [[Категория:Файлы К удалению]]
}}
8dfc63bde88501a508e9855453e337dc0ed6c4ac
34
33
2024-04-29T09:26:17Z
Genka Barboskin
2
wikitext
text/x-wiki
{{ambox
| name = {{{name|К удалению}}}
| type = speedy
| id = request_for_deletion
| image = [[Файл:Ambox_warning_pn.svg.png|40px|alt=|link=]]
| text = '''{{#switch: ~{{NAMESPACE}}
| ~Файл = Этот файл
| ~Шаблон = Этот шаблон
| ~Категория = Эту категорию
| ~Участник = Эту страницу участника
| ~ = Эту статью
| Эту страницу
}} - кандидат на удаление.'''
| text-small = {{#if: {{{1|}}}
| Пояснение причин и соответствующее обсуждение вы можете найти на странице {{nobr|[[Монетопедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}#{{#if: {{{2|}}}
| {{{2}}}
| {{FULLPAGENAME}}
}}{{!}}Википедия:К удалению/{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}]]}}.
| <span class="error">Не указана страница, на которой происходит обсуждение.</span><includeonly>[[Категория:Страницы с номинациями, местоположение которых не указано|У]]</includeonly>
}}<br>Пока процесс обсуждения не завершён, {{#if: {{NAMESPACE}}
| страницу
| статью
}} на исправление статьи даётся 3 дня, если в течении срока статья не будет исправлена, то она будет удалена.
<hr {{#ifeq: {{NAMESPACE}}
| {{ns:14}}
| class="group-closer-show group-sysop-show"
}}>
{{#ifeq: {{{1}}}
| {{#time: Y-m-d}}
| ''Номинатору: [{{fullurl:Монетопедия:К удалению/{{#time: j xg Y | {{{1}}} }}|action=edit§ion=new&preview=no&preloadtitle=%5B%5B{{#switch: {{NAMESPACE}}
| {{ns:6}} | {{ns:14}} = %3A
}}{{urlencode:{{FULLPAGENAME}}}}%5D%5D&editintro=template:editintro/КУ}} добавить секцию обсуждения]''.<br>
}}
| {{Сортировка: КУ}}[[Категория:Кандидаты на удаление]][[Категория:Кандидаты на удаление по дате номинации|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]]{{#ifeq: {{Просроченные подведения итогов|{{#iferror: {{#time: j xg Y | {{{1}}} }}
| {{{1}}}
| {{#time: j xg Y | {{{1}}} }}
}}}}
| true
| [[Категория:Просроченные подведения итогов по удалению страниц|{{#if: {{{1}}}
| {{#time: Y-m-d | {{Date Converter|{{{1}}}}} }}
| {{FULLPAGENAME}}
}}]][[Категория:Просроченные подведения итогов по удалению страниц по алфавиту|{{FULLPAGENAME}}]]
}}{{#switch: ~{{NAMESPACE}}
| ~Файл = [[Категория:Файлы К удалению]]
}}
}}
e4712c49401c32042dac2aada8ca0484e4a4aaf6
Модуль:Mbox
828
17
21
2024-04-29T03:22:14Z
Genka Barboskin
2
Новая страница: «-- <nowiki> local Mbox = {} local getArgs = require('Dev:Arguments').getArgs local i18n = require('Dev:I18n').loadMessages('Mbox') local localCSS = mw.loadData('Module:Mbox/data').localStyle function Mbox.main(frame) local args = getArgs(frame) -- styles local styles = {} styles['border-left-color'] = i18n:parameter('bordercolor', args) styles['background-color'] = i18n:parameter('bgcolor', args) -- images local image = i18n:parameter('image', args)...»
Scribunto
text/plain
-- <nowiki>
local Mbox = {}
local getArgs = require('Dev:Arguments').getArgs
local i18n = require('Dev:I18n').loadMessages('Mbox')
local localCSS = mw.loadData('Module:Mbox/data').localStyle
function Mbox.main(frame)
local args = getArgs(frame)
-- styles
local styles = {}
styles['border-left-color'] = i18n:parameter('bordercolor', args)
styles['background-color'] = i18n:parameter('bgcolor', args)
-- images
local image = i18n:parameter('image', args) or ''
local imagewidth = i18n:parameter('imagewidth', args) or '80px'
local imagelink = '|link='
local imagelinkarg = i18n:parameter('imagelink', args)
if imagelinkarg then
imagelink = imagelink .. imagelinkarg
end
local imagewikitext = ('%sFile:%s|%s%s' .. ']]'):format('[[', image, imagewidth, imagelink)
-- id for closure
local id = i18n:parameter('id', args) or 'mbox'
local typeclass = i18n:parameter('type', args)
local container = mw.html.create('div')
:addClass('mbox')
:addClass(typeclass and ('mbox-type-' .. typeclass))
:addClass(i18n:parameter('class', args))
:css(localCSS['mbox'])
:css(styles)
:cssText(i18n:parameter('style', args))
local content = container:tag('div')
:addClass('mbox__content')
:css(localCSS['mbox__content'])
local collapsed = i18n:parameter('collapsed', args)
if image ~= '' then
local image = content:tag('div')
:addClass('mbox__content__image')
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:css(localCSS['mbox__content__image'])
:wikitext(imagewikitext)
if collapsed then
image:addClass('mw-collapsed')
end
end
local contentwrapper = content:tag('div')
:addClass('mbox__content__wrapper')
:css(localCSS['mbox__content__wrapper'])
local header = i18n:parameter('header', args)
if header then
contentwrapper:tag('div')
:addClass('mbox__content__header')
:css(localCSS['mbox__content__header'])
:wikitext(header)
end
local textarg = i18n:parameter('text', args)
if textarg then
local text = contentwrapper:tag('div')
:addClass('mbox__content__text')
:css(localCSS['mbox__content__text'])
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:wikitext(textarg)
if collapsed then
text:addClass('mw-collapsed')
end
local comment = i18n:parameter('comment', args)
if comment then
text:tag('div')
:addClass('mbox__content__text__comment')
:css(localCSS['mbox__content__text__comment'])
:wikitext(comment)
end
end
contentwrapper:tag('span')
:addClass('mbox__close')
:addClass('mw-customtoggle-' .. id)
:css(localCSS['mbox__close'])
:attr('title', i18n:msg('dismiss'))
local asidearg = i18n:parameter('aside', args)
if asidearg then
local aside = content:tag('div')
:addClass('mbox__content__aside')
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:css(localCSS['mbox__content__aside'])
:wikitext(asidearg)
if collapsed then
aside:addClass('mw-collapsed')
end
end
return container
end
return Mbox
f0bc70b0b38ffd60a87a6ecd4fcb9e8fd29f2b94
24
21
2024-04-29T03:26:17Z
Genka Barboskin
2
Scribunto
text/plain
-- <nowiki>
local Mbox = {}
local getArgs = require('Module:Arguments').getArgs
local i18n = require('Module:I18n').loadMessages('Mbox')
local localCSS = mw.loadData('Module:Mbox/data').localStyle
function Mbox.main(frame)
local args = getArgs(frame)
-- styles
local styles = {}
styles['border-left-color'] = i18n:parameter('bordercolor', args)
styles['background-color'] = i18n:parameter('bgcolor', args)
-- images
local image = i18n:parameter('image', args) or ''
local imagewidth = i18n:parameter('imagewidth', args) or '80px'
local imagelink = '|link='
local imagelinkarg = i18n:parameter('imagelink', args)
if imagelinkarg then
imagelink = imagelink .. imagelinkarg
end
local imagewikitext = ('%sFile:%s|%s%s' .. ']]'):format('[[', image, imagewidth, imagelink)
-- id for closure
local id = i18n:parameter('id', args) or 'mbox'
local typeclass = i18n:parameter('type', args)
local container = mw.html.create('div')
:addClass('mbox')
:addClass(typeclass and ('mbox-type-' .. typeclass))
:addClass(i18n:parameter('class', args))
:css(localCSS['mbox'])
:css(styles)
:cssText(i18n:parameter('style', args))
local content = container:tag('div')
:addClass('mbox__content')
:css(localCSS['mbox__content'])
local collapsed = i18n:parameter('collapsed', args)
if image ~= '' then
local image = content:tag('div')
:addClass('mbox__content__image')
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:css(localCSS['mbox__content__image'])
:wikitext(imagewikitext)
if collapsed then
image:addClass('mw-collapsed')
end
end
local contentwrapper = content:tag('div')
:addClass('mbox__content__wrapper')
:css(localCSS['mbox__content__wrapper'])
local header = i18n:parameter('header', args)
if header then
contentwrapper:tag('div')
:addClass('mbox__content__header')
:css(localCSS['mbox__content__header'])
:wikitext(header)
end
local textarg = i18n:parameter('text', args)
if textarg then
local text = contentwrapper:tag('div')
:addClass('mbox__content__text')
:css(localCSS['mbox__content__text'])
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:wikitext(textarg)
if collapsed then
text:addClass('mw-collapsed')
end
local comment = i18n:parameter('comment', args)
if comment then
text:tag('div')
:addClass('mbox__content__text__comment')
:css(localCSS['mbox__content__text__comment'])
:wikitext(comment)
end
end
contentwrapper:tag('span')
:addClass('mbox__close')
:addClass('mw-customtoggle-' .. id)
:css(localCSS['mbox__close'])
:attr('title', i18n:msg('dismiss'))
local asidearg = i18n:parameter('aside', args)
if asidearg then
local aside = content:tag('div')
:addClass('mbox__content__aside')
:addClass('mw-collapsible')
:attr('id', 'mw-customcollapsible-' .. id)
:css(localCSS['mbox__content__aside'])
:wikitext(asidearg)
if collapsed then
aside:addClass('mw-collapsed')
end
end
return container
end
return Mbox
4a9f42fd8e5448732e7810a0696d2da20d9d635d
Модуль:Mbox/data
828
18
22
2024-04-29T03:22:48Z
Genka Barboskin
2
Новая страница: «local localStyle = { ['mbox'] = { ['display'] = 'flex', ['position'] = 'relative', ['background-color'] = 'transparent', ['border'] = '1px solid #d6d6d6', ['border-left-width'] = '8px', ['border-left-color'] = '#d6d6d6', ['border-radius'] = '3px', ['margin-bottom'] = '5px', ['min-height'] = '32px' }, ['mbox__content'] = { ['display'] = 'table', ['box-sizing'] = 'border-box', ['width'] = '100%', ['padding'] = '8px 15px' }, ['mbox__content__image'] = { ['displ...»
Scribunto
text/plain
local localStyle = {
['mbox'] = {
['display'] = 'flex',
['position'] = 'relative',
['background-color'] = 'transparent',
['border'] = '1px solid #d6d6d6',
['border-left-width'] = '8px',
['border-left-color'] = '#d6d6d6',
['border-radius'] = '3px',
['margin-bottom'] = '5px',
['min-height'] = '32px'
},
['mbox__content'] = {
['display'] = 'table',
['box-sizing'] = 'border-box',
['width'] = '100%',
['padding'] = '8px 15px'
},
['mbox__content__image'] = {
['display'] = 'table-cell',
['width'] = '40px',
['height'] = '100%',
['text-align'] = 'center',
['vertical-align'] = 'middle',
['padding-right'] = '15px'
},
['mbox__content__wrapper'] = {
['display'] = 'table-cell',
['vertical-align'] = 'middle'
},
['mbox__content__header'] = {
['display'] = 'block',
['font-weight'] = 'bold'
},
['mbox__content__text'] = {
['display'] = 'block'
},
['mbox__content__text__comment'] = {
['font-size'] = 'small'
},
['mbox__content__aside'] = {
['display'] = 'table-cell',
['width'] = '100px',
['vertical-align'] = 'middle',
['text-align'] = 'center',
['padding-left'] = '15px',
['border-left'] = '1px solid #d6d6d6'
},
['mbox__close'] = {
['position'] = 'absolute',
['right'] = '0',
['top'] = '0',
['padding'] = '2px 7px',
['font-weight'] = 'bold',
['font-size'] = '16px',
['color'] = '#bbb',
['cursor'] = 'pointer',
['transition'] = 'all .15s ease-in'
}
}
return { localStyle = localStyle }
06266c68939db3143974070ef45a6becef31dac9
Модуль:I18n
828
20
25
2024-04-29T03:26:40Z
Genka Barboskin
2
Новая страница: «--- I18n library for message storage in Lua datastores. -- The module is designed to enable message separation from modules & -- templates. It has support for handling language fallbacks. This -- module is a Lua port of [[I18n-js]] and i18n modules that can be loaded -- by it are editable through [[I18nEdit]]. -- -- @module i18n -- @version 1.4.0 -- @require Module:Entrypoint -- @require Module:Fallbacklist -- @author...»
Scribunto
text/plain
--- I18n library for message storage in Lua datastores.
-- The module is designed to enable message separation from modules &
-- templates. It has support for handling language fallbacks. This
-- module is a Lua port of [[I18n-js]] and i18n modules that can be loaded
-- by it are editable through [[I18nEdit]].
--
-- @module i18n
-- @version 1.4.0
-- @require Module:Entrypoint
-- @require Module:Fallbacklist
-- @author [[User:KockaAdmiralac|KockaAdmiralac]]
-- @author [[User:Speedit|Speedit]]
-- @attribution [[User:Cqm|Cqm]]
-- @release stable
-- @see [[I18n|I18n guide]]
-- @see [[I18n-js]]
-- @see [[I18nEdit]]
-- <nowiki>
local i18n, _i18n = {}, {}
-- Module variables & dependencies.
local title = mw.title.getCurrentTitle()
local fallbacks = require('Dev:Fallbacklist')
local entrypoint = require('Dev:Entrypoint')
local uselang
--- Argument substitution as $n where n > 0.
-- @function _i18n.handleArgs
-- @param {string} msg Message to substitute arguments into.
-- @param {table} args Arguments table to substitute.
-- @return {string} Resulting message.
-- @local
function _i18n.handleArgs(msg, args)
for i, a in ipairs(args) do
msg = (string.gsub(msg, '%$' .. tostring(i), tostring(a)))
end
return msg
end
--- Checks whether a language code is valid.
-- @function _i18n.isValidCode
-- @param {string} code Language code to check.
-- @return {boolean} Whether the language code is valid.
-- @local
function _i18n.isValidCode(code)
return type(code) == 'string' and #mw.language.fetchLanguageName(code) ~= 0
end
--- Checks whether a message contains unprocessed wikitext.
-- Used to optimise message getter by not preprocessing pure text.
-- @function _i18n.isWikitext
-- @param {string} msg Message to check.
-- @return {boolean} Whether the message contains wikitext.
function _i18n.isWikitext(msg)
return
type(msg) == 'string' and
(
msg:find('%-%-%-%-') or
msg:find('%f[^\n%z][;:*#] ') or
msg:find('%f[^\n%z]==* *[^\n|]+ =*=%f[\n]') or
msg:find('%b<>') or msg:find('\'\'') or
msg:find('%[%b[]%]') or msg:find('{%b{}}')
)
end
--- I18n datastore class.
-- This is used to control language translation and access to individual
-- messages. The datastore instance provides language and message
-- getter-setter methods, which can be used to internationalize Lua modules.
-- The language methods (any ending in `Lang`) are all **chainable**.
-- @type Data
local Data = {}
Data.__index = Data
--- Datastore message getter utility.
-- This method returns localized messages from the datastore corresponding
-- to a `key`. These messages may have `$n` parameters, which can be
-- replaced by optional argument strings supplied by the `msg` call.
--
-- This function supports [[Lua reference manual#named_arguments|named
-- arguments]]. The named argument syntax is more versatile despite its
-- verbosity; it can be used to select message language & source(s).
-- @function Data:msg
-- @usage
--
-- ds:msg{
-- key = 'message-name',
-- lang = '',
-- args = {...},
-- sources = {}
-- }
--
-- @usage
--
-- ds:msg('message-name', ...)
--
-- @param {string|table} opts Message configuration or key.
-- @param[opt] {string} opts.key Message key to return from the
-- datastore.
-- @param[opt] {table} opts.args Arguments to substitute into the
-- message (`$n`).
-- @param[opt] {table} opts.sources Source names to limit to (see
-- `Data:fromSources`).
-- @param[opt] {table} opts.lang Temporary language to use (see
-- `Data:inLang`).
-- @param[opt] {string} ... Arguments to substitute into the message
-- (`$n`).
-- @error[115] {string} 'missing arguments in Data:msg'
-- @return {string} Localised datastore message or `'<key>'`.
function Data:msg(opts, ...)
local frame = mw.getCurrentFrame()
-- Argument normalization.
if not self or not opts then
error('missing arguments in Data:msg')
end
local key = type(opts) == 'table' and opts.key or opts
local args = opts.args or {...}
-- Configuration parameters.
if opts.sources then
self:fromSources(unpack(opts.sources))
end
if opts.lang then
self:inLang(opts.lang)
end
-- Source handling.
local source_n = self.tempSources or self._sources
local source_i = {}
for n, i in pairs(source_n) do
source_i[i] = n
end
self.tempSources = nil
-- Language handling.
local lang = self.tempLang or self.defaultLang
self.tempLang = nil
-- Message fetching.
local msg
for i, messages in ipairs(self._messages) do
-- Message data.
local msg = (messages[lang] or {})[key]
-- Fallback support (experimental).
for _, l in ipairs((fallbacks[lang] or {})) do
if msg == nil then
msg = (messages[l] or {})[key]
end
end
-- Internal fallback to 'en'.
msg = msg ~= nil and msg or messages.en[key]
-- Handling argument substitution from Lua.
if msg and source_i[i] and #args > 0 then
msg = _i18n.handleArgs(msg, args)
end
if msg and source_i[i] and lang ~= 'qqx' then
return frame and _i18n.isWikitext(msg)
and frame:preprocess(mw.text.trim(msg))
or mw.text.trim(msg)
end
end
return mw.text.nowiki('<' .. key .. '>')
end
--- Datastore template parameter getter utility.
-- This method, given a table of arguments, tries to find a parameter's
-- localized name in the datastore and returns its value, or nil if
-- not present.
--
-- This method always uses the wiki's content language.
-- @function Data:parameter
-- @param {string} parameter Parameter's key in the datastore
-- @param {table} args Arguments to find the parameter in
-- @error[176] {string} 'missing arguments in Data:parameter'
-- @return {string|nil} Parameter's value or nil if not present
function Data:parameter(key, args)
-- Argument normalization.
if not self or not key or not args then
error('missing arguments in Data:parameter')
end
local contentLang = mw.language.getContentLanguage():getCode()
-- Message fetching.
for i, messages in ipairs(self._messages) do
local msg = (messages[contentLang] or {})[key]
if msg ~= nil and args[msg] ~= nil then
return args[msg]
end
for _, l in ipairs((fallbacks[contentLang] or {})) do
if msg == nil or args[msg] == nil then
-- Check next fallback.
msg = (messages[l] or {})[key]
else
-- A localized message was found.
return args[msg]
end
end
-- Fallback to English.
msg = messages.en[key]
if msg ~= nil and args[msg] ~= nil then
return args[msg]
end
end
end
--- Datastore temporary source setter to a specificed subset of datastores.
-- By default, messages are fetched from the datastore in the same
-- order of priority as `i18n.loadMessages`.
-- @function Data:fromSource
-- @param {string} ... Source name(s) to use.
-- @return {Data} Datastore instance.
function Data:fromSource(...)
local c = select('#', ...)
if c ~= 0 then
self.tempSources = {}
for i = 1, c do
local n = select(i, ...)
if type(n) == 'string' and type(self._sources[n]) == 'number' then
self.tempSources[n] = self._sources[n]
end
end
end
return self
end
--- Datastore default language getter.
-- @function Data:getLang
-- @return {string} Default language to serve datastore messages in.
function Data:getLang()
return self.defaultLang
end
--- Datastore language setter to `wgUserLanguage`.
-- @function Data:useUserLang
-- @return {Data} Datastore instance.
-- @note Scribunto only registers `wgUserLanguage` when an
-- invocation is at the top of the call stack.
function Data:useUserLang()
self.defaultLang = i18n.getLang() or self.defaultLang
return self
end
--- Datastore language setter to `wgContentLanguage`.
-- @function Data:useContentLang
-- @return {Data} Datastore instance.
function Data:useContentLang()
self.defaultLang = mw.language.getContentLanguage():getCode()
return self
end
--- Datastore language setter to specificed language.
-- @function Data:useLang
-- @param {string} code Language code to use.
-- @return {Data} Datastore instance.
function Data:useLang(code)
self.defaultLang = _i18n.isValidCode(code)
and code
or self.defaultLang
return self
end
--- Temporary datastore language setter to `wgUserLanguage`.
-- The datastore language reverts to the default language in the next
-- @{Data:msg} call.
-- @function Data:inUserLang
-- @return {Data} Datastore instance.
function Data:inUserLang()
self.tempLang = i18n.getLang() or self.tempLang
return self
end
--- Temporary datastore language setter to `wgContentLanguage`.
-- Only affects the next @{Data:msg} call.
-- @function Data:inContentLang
-- @return {Data} Datastore instance.
function Data:inContentLang()
self.tempLang = mw.language.getContentLanguage():getCode()
return self
end
--- Temporary datastore language setter to a specificed language.
-- Only affects the next @{Data:msg} call.
-- @function Data:inLang
-- @param {string} code Language code to use.
-- @return {Data} Datastore instance.
function Data:inLang(code)
self.tempLang = _i18n.isValidCode(code)
and code
or self.tempLang
return self
end
-- Package functions.
--- Localized message getter by key.
-- Can be used to fetch messages in a specific language code through `uselang`
-- parameter. Extra numbered parameters can be supplied for substitution into
-- the datastore message.
-- @function i18n.getMsg
-- @param {table} frame Frame table from invocation.
-- @param {table} frame.args Metatable containing arguments.
-- @param {string} frame.args[1] ROOTPAGENAME of i18n submodule.
-- @param {string} frame.args[2] Key of i18n message.
-- @param[opt] {string} frame.args.lang Default language of message.
-- @error[271] 'missing arguments in i18n.getMsg'
-- @return {string} I18n message in localised language.
-- @usage {{i18n|getMsg|source|key|arg1|arg2|uselang {{=}} code}}
function i18n.getMsg(frame)
if
not frame or
not frame.args or
not frame.args[1] or
not frame.args[2]
then
error('missing arguments in i18n.getMsg')
end
local source = frame.args[1]
local key = frame.args[2]
-- Pass through extra arguments.
local repl = {}
for i, a in ipairs(frame.args) do
if i >= 3 then
repl[i-2] = a
end
end
-- Load message data.
local ds = i18n.loadMessages(source)
-- Pass through language argument.
ds:inLang(frame.args.uselang)
-- Return message.
return ds:msg { key = key, args = repl }
end
--- I18n message datastore loader.
-- @function i18n.loadMessages
-- @param {string} ... ROOTPAGENAME/path for target i18n
-- submodules.
-- @error[322] {string} 'no source supplied to i18n.loadMessages'
-- @return {table} I18n datastore instance.
-- @usage require('Dev:I18n').loadMessages('1', '2')
function i18n.loadMessages(...)
local ds
local i = 0
local s = {}
for j = 1, select('#', ...) do
local source = select(j, ...)
if type(source) == 'string' and source ~= '' then
i = i + 1
s[source] = i
if not ds then
-- Instantiate datastore.
ds = {}
ds._messages = {}
-- Set default language.
setmetatable(ds, Data)
ds:useUserLang()
end
source = string.gsub(source, '^.', mw.ustring.upper)
source = mw.ustring.find(source, ':')
and source
or 'Dev:' .. source .. '/i18n'
ds._messages[i] = mw.loadData(source)
end
end
if not ds then
error('no source supplied to i18n.loadMessages')
else
-- Attach source index map.
ds._sources = s
-- Return datastore instance.
return ds
end
end
--- Language code getter.
-- Can validate a template's language code through `uselang` parameter.
-- @function i18n.getLang
-- @usage {{i18n|getLang|uselang {{=}} code}}
-- @return {string} Language code.
function i18n.getLang()
local frame = mw.getCurrentFrame() or {}
local parentFrame = frame.getParent and frame:getParent() or {}
local code = mw.language.getContentLanguage():getCode()
local subPage = title.subpageText
-- Language argument test.
local langOverride =
(frame.args or {}).uselang or
(parentFrame.args or {}).uselang
if _i18n.isValidCode(langOverride) then
code = langOverride
-- Subpage language test.
elseif title.isSubpage and _i18n.isValidCode(subPage) then
code = _i18n.isValidCode(subPage) and subPage or code
-- User language test.
elseif parentFrame.preprocess or frame.preprocess then
uselang = uselang
or parentFrame.preprocess
and parentFrame:preprocess('{{int:lang}}')
or frame:preprocess('{{int:lang}}')
local decodedLang = mw.text.decode(uselang)
if decodedLang ~= '<lang>' and decodedLang ~= '⧼lang⧽' then
code = decodedLang == '(lang)'
and 'qqx'
or uselang
end
end
return code
end
--- Template wrapper for [[Template:I18n]].
-- @function i18n.main
-- @param {table} frame Frame invocation object.
-- @return {string} Module output in template context.
-- @usage {{#invoke:i18n|main}}
i18n.main = entrypoint(i18n)
return i18n
-- </nowiki>
06ac09a689dcc2ffb68ca964373050f6cc8e0fbf
26
25
2024-04-29T03:27:10Z
Genka Barboskin
2
Scribunto
text/plain
--- I18n library for message storage in Lua datastores.
-- The module is designed to enable message separation from modules &
-- templates. It has support for handling language fallbacks. This
-- module is a Lua port of [[I18n-js]] and i18n modules that can be loaded
-- by it are editable through [[I18nEdit]].
--
-- @module i18n
-- @version 1.4.0
-- @require Module:Entrypoint
-- @require Module:Fallbacklist
-- @author [[User:KockaAdmiralac|KockaAdmiralac]]
-- @author [[User:Speedit|Speedit]]
-- @attribution [[User:Cqm|Cqm]]
-- @release stable
-- @see [[I18n|I18n guide]]
-- @see [[I18n-js]]
-- @see [[I18nEdit]]
-- <nowiki>
local i18n, _i18n = {}, {}
-- Module variables & dependencies.
local title = mw.title.getCurrentTitle()
local fallbacks = require('Module:Fallbacklist')
local entrypoint = require('Module:Entrypoint')
local uselang
--- Argument substitution as $n where n > 0.
-- @function _i18n.handleArgs
-- @param {string} msg Message to substitute arguments into.
-- @param {table} args Arguments table to substitute.
-- @return {string} Resulting message.
-- @local
function _i18n.handleArgs(msg, args)
for i, a in ipairs(args) do
msg = (string.gsub(msg, '%$' .. tostring(i), tostring(a)))
end
return msg
end
--- Checks whether a language code is valid.
-- @function _i18n.isValidCode
-- @param {string} code Language code to check.
-- @return {boolean} Whether the language code is valid.
-- @local
function _i18n.isValidCode(code)
return type(code) == 'string' and #mw.language.fetchLanguageName(code) ~= 0
end
--- Checks whether a message contains unprocessed wikitext.
-- Used to optimise message getter by not preprocessing pure text.
-- @function _i18n.isWikitext
-- @param {string} msg Message to check.
-- @return {boolean} Whether the message contains wikitext.
function _i18n.isWikitext(msg)
return
type(msg) == 'string' and
(
msg:find('%-%-%-%-') or
msg:find('%f[^\n%z][;:*#] ') or
msg:find('%f[^\n%z]==* *[^\n|]+ =*=%f[\n]') or
msg:find('%b<>') or msg:find('\'\'') or
msg:find('%[%b[]%]') or msg:find('{%b{}}')
)
end
--- I18n datastore class.
-- This is used to control language translation and access to individual
-- messages. The datastore instance provides language and message
-- getter-setter methods, which can be used to internationalize Lua modules.
-- The language methods (any ending in `Lang`) are all **chainable**.
-- @type Data
local Data = {}
Data.__index = Data
--- Datastore message getter utility.
-- This method returns localized messages from the datastore corresponding
-- to a `key`. These messages may have `$n` parameters, which can be
-- replaced by optional argument strings supplied by the `msg` call.
--
-- This function supports [[Lua reference manual#named_arguments|named
-- arguments]]. The named argument syntax is more versatile despite its
-- verbosity; it can be used to select message language & source(s).
-- @function Data:msg
-- @usage
--
-- ds:msg{
-- key = 'message-name',
-- lang = '',
-- args = {...},
-- sources = {}
-- }
--
-- @usage
--
-- ds:msg('message-name', ...)
--
-- @param {string|table} opts Message configuration or key.
-- @param[opt] {string} opts.key Message key to return from the
-- datastore.
-- @param[opt] {table} opts.args Arguments to substitute into the
-- message (`$n`).
-- @param[opt] {table} opts.sources Source names to limit to (see
-- `Data:fromSources`).
-- @param[opt] {table} opts.lang Temporary language to use (see
-- `Data:inLang`).
-- @param[opt] {string} ... Arguments to substitute into the message
-- (`$n`).
-- @error[115] {string} 'missing arguments in Data:msg'
-- @return {string} Localised datastore message or `'<key>'`.
function Data:msg(opts, ...)
local frame = mw.getCurrentFrame()
-- Argument normalization.
if not self or not opts then
error('missing arguments in Data:msg')
end
local key = type(opts) == 'table' and opts.key or opts
local args = opts.args or {...}
-- Configuration parameters.
if opts.sources then
self:fromSources(unpack(opts.sources))
end
if opts.lang then
self:inLang(opts.lang)
end
-- Source handling.
local source_n = self.tempSources or self._sources
local source_i = {}
for n, i in pairs(source_n) do
source_i[i] = n
end
self.tempSources = nil
-- Language handling.
local lang = self.tempLang or self.defaultLang
self.tempLang = nil
-- Message fetching.
local msg
for i, messages in ipairs(self._messages) do
-- Message data.
local msg = (messages[lang] or {})[key]
-- Fallback support (experimental).
for _, l in ipairs((fallbacks[lang] or {})) do
if msg == nil then
msg = (messages[l] or {})[key]
end
end
-- Internal fallback to 'en'.
msg = msg ~= nil and msg or messages.en[key]
-- Handling argument substitution from Lua.
if msg and source_i[i] and #args > 0 then
msg = _i18n.handleArgs(msg, args)
end
if msg and source_i[i] and lang ~= 'qqx' then
return frame and _i18n.isWikitext(msg)
and frame:preprocess(mw.text.trim(msg))
or mw.text.trim(msg)
end
end
return mw.text.nowiki('<' .. key .. '>')
end
--- Datastore template parameter getter utility.
-- This method, given a table of arguments, tries to find a parameter's
-- localized name in the datastore and returns its value, or nil if
-- not present.
--
-- This method always uses the wiki's content language.
-- @function Data:parameter
-- @param {string} parameter Parameter's key in the datastore
-- @param {table} args Arguments to find the parameter in
-- @error[176] {string} 'missing arguments in Data:parameter'
-- @return {string|nil} Parameter's value or nil if not present
function Data:parameter(key, args)
-- Argument normalization.
if not self or not key or not args then
error('missing arguments in Data:parameter')
end
local contentLang = mw.language.getContentLanguage():getCode()
-- Message fetching.
for i, messages in ipairs(self._messages) do
local msg = (messages[contentLang] or {})[key]
if msg ~= nil and args[msg] ~= nil then
return args[msg]
end
for _, l in ipairs((fallbacks[contentLang] or {})) do
if msg == nil or args[msg] == nil then
-- Check next fallback.
msg = (messages[l] or {})[key]
else
-- A localized message was found.
return args[msg]
end
end
-- Fallback to English.
msg = messages.en[key]
if msg ~= nil and args[msg] ~= nil then
return args[msg]
end
end
end
--- Datastore temporary source setter to a specificed subset of datastores.
-- By default, messages are fetched from the datastore in the same
-- order of priority as `i18n.loadMessages`.
-- @function Data:fromSource
-- @param {string} ... Source name(s) to use.
-- @return {Data} Datastore instance.
function Data:fromSource(...)
local c = select('#', ...)
if c ~= 0 then
self.tempSources = {}
for i = 1, c do
local n = select(i, ...)
if type(n) == 'string' and type(self._sources[n]) == 'number' then
self.tempSources[n] = self._sources[n]
end
end
end
return self
end
--- Datastore default language getter.
-- @function Data:getLang
-- @return {string} Default language to serve datastore messages in.
function Data:getLang()
return self.defaultLang
end
--- Datastore language setter to `wgUserLanguage`.
-- @function Data:useUserLang
-- @return {Data} Datastore instance.
-- @note Scribunto only registers `wgUserLanguage` when an
-- invocation is at the top of the call stack.
function Data:useUserLang()
self.defaultLang = i18n.getLang() or self.defaultLang
return self
end
--- Datastore language setter to `wgContentLanguage`.
-- @function Data:useContentLang
-- @return {Data} Datastore instance.
function Data:useContentLang()
self.defaultLang = mw.language.getContentLanguage():getCode()
return self
end
--- Datastore language setter to specificed language.
-- @function Data:useLang
-- @param {string} code Language code to use.
-- @return {Data} Datastore instance.
function Data:useLang(code)
self.defaultLang = _i18n.isValidCode(code)
and code
or self.defaultLang
return self
end
--- Temporary datastore language setter to `wgUserLanguage`.
-- The datastore language reverts to the default language in the next
-- @{Data:msg} call.
-- @function Data:inUserLang
-- @return {Data} Datastore instance.
function Data:inUserLang()
self.tempLang = i18n.getLang() or self.tempLang
return self
end
--- Temporary datastore language setter to `wgContentLanguage`.
-- Only affects the next @{Data:msg} call.
-- @function Data:inContentLang
-- @return {Data} Datastore instance.
function Data:inContentLang()
self.tempLang = mw.language.getContentLanguage():getCode()
return self
end
--- Temporary datastore language setter to a specificed language.
-- Only affects the next @{Data:msg} call.
-- @function Data:inLang
-- @param {string} code Language code to use.
-- @return {Data} Datastore instance.
function Data:inLang(code)
self.tempLang = _i18n.isValidCode(code)
and code
or self.tempLang
return self
end
-- Package functions.
--- Localized message getter by key.
-- Can be used to fetch messages in a specific language code through `uselang`
-- parameter. Extra numbered parameters can be supplied for substitution into
-- the datastore message.
-- @function i18n.getMsg
-- @param {table} frame Frame table from invocation.
-- @param {table} frame.args Metatable containing arguments.
-- @param {string} frame.args[1] ROOTPAGENAME of i18n submodule.
-- @param {string} frame.args[2] Key of i18n message.
-- @param[opt] {string} frame.args.lang Default language of message.
-- @error[271] 'missing arguments in i18n.getMsg'
-- @return {string} I18n message in localised language.
-- @usage {{i18n|getMsg|source|key|arg1|arg2|uselang {{=}} code}}
function i18n.getMsg(frame)
if
not frame or
not frame.args or
not frame.args[1] or
not frame.args[2]
then
error('missing arguments in i18n.getMsg')
end
local source = frame.args[1]
local key = frame.args[2]
-- Pass through extra arguments.
local repl = {}
for i, a in ipairs(frame.args) do
if i >= 3 then
repl[i-2] = a
end
end
-- Load message data.
local ds = i18n.loadMessages(source)
-- Pass through language argument.
ds:inLang(frame.args.uselang)
-- Return message.
return ds:msg { key = key, args = repl }
end
--- I18n message datastore loader.
-- @function i18n.loadMessages
-- @param {string} ... ROOTPAGENAME/path for target i18n
-- submodules.
-- @error[322] {string} 'no source supplied to i18n.loadMessages'
-- @return {table} I18n datastore instance.
-- @usage require('Dev:I18n').loadMessages('1', '2')
function i18n.loadMessages(...)
local ds
local i = 0
local s = {}
for j = 1, select('#', ...) do
local source = select(j, ...)
if type(source) == 'string' and source ~= '' then
i = i + 1
s[source] = i
if not ds then
-- Instantiate datastore.
ds = {}
ds._messages = {}
-- Set default language.
setmetatable(ds, Data)
ds:useUserLang()
end
source = string.gsub(source, '^.', mw.ustring.upper)
source = mw.ustring.find(source, ':')
and source
or 'Dev:' .. source .. '/i18n'
ds._messages[i] = mw.loadData(source)
end
end
if not ds then
error('no source supplied to i18n.loadMessages')
else
-- Attach source index map.
ds._sources = s
-- Return datastore instance.
return ds
end
end
--- Language code getter.
-- Can validate a template's language code through `uselang` parameter.
-- @function i18n.getLang
-- @usage {{i18n|getLang|uselang {{=}} code}}
-- @return {string} Language code.
function i18n.getLang()
local frame = mw.getCurrentFrame() or {}
local parentFrame = frame.getParent and frame:getParent() or {}
local code = mw.language.getContentLanguage():getCode()
local subPage = title.subpageText
-- Language argument test.
local langOverride =
(frame.args or {}).uselang or
(parentFrame.args or {}).uselang
if _i18n.isValidCode(langOverride) then
code = langOverride
-- Subpage language test.
elseif title.isSubpage and _i18n.isValidCode(subPage) then
code = _i18n.isValidCode(subPage) and subPage or code
-- User language test.
elseif parentFrame.preprocess or frame.preprocess then
uselang = uselang
or parentFrame.preprocess
and parentFrame:preprocess('{{int:lang}}')
or frame:preprocess('{{int:lang}}')
local decodedLang = mw.text.decode(uselang)
if decodedLang ~= '<lang>' and decodedLang ~= '⧼lang⧽' then
code = decodedLang == '(lang)'
and 'qqx'
or uselang
end
end
return code
end
--- Template wrapper for [[Template:I18n]].
-- @function i18n.main
-- @param {table} frame Frame invocation object.
-- @return {string} Module output in template context.
-- @usage {{#invoke:i18n|main}}
i18n.main = entrypoint(i18n)
return i18n
-- </nowiki>
6f88774597ce3341e37a82e0b31ad7f5853782ed
27
26
2024-04-29T03:29:41Z
Genka Barboskin
2
Scribunto
text/plain
-- <nowiki>
return {
["_metadata"] = {
["order"] = {
"aside",
"bgcolor",
"bordercolor",
"class",
"collapsed",
"comment",
"dismiss",
"header",
"id",
"image",
"imagelink",
"imagewidth",
"style",
"text",
"type"
}
},
["en"] = {
["aside"] = "aside",
["bgcolor"] = "bgcolor",
["bordercolor"] = "bordercolor",
["class"] = "class",
["collapsed"] = "collapsed",
["comment"] = "comment",
["dismiss"] = "Dismiss",
["header"] = "header",
["id"] = "id",
["image"] = "image",
["imagelink"] = "imagelink",
["imagewidth"] = "imagewidth",
["style"] = "style",
["text"] = "text",
["type"] = "type"
},
["de"] = {
["aside"] = "nebenbemerkung",
["bgcolor"] = "hintergrundfarbe",
["bordercolor"] = "randfarbe",
["class"] = "klasse",
["collapsed"] = "eingeklappt",
["comment"] = "Kommentar",
["dismiss"] = "Verstecken",
["header"] = "Titel",
["id"] = "id",
["image"] = "bild",
["imagelink"] = "bildlink",
["imagewidth"] = "bildbreite",
["style"] = "style",
["text"] = "Text",
["type"] = "typ"
},
["et"] = {
["aside"] = "kõrval",
["bgcolor"] = "taustavärv",
["bordercolor"] = "piirivärv",
["class"] = "klass",
["comment"] = "kommentaar",
["dismiss"] = "Loobu",
["id"] = "id",
["image"] = "pilt",
["imagelink"] = "pildilink",
["imagewidth"] = "pildisuurus",
["style"] = "stiil",
["text"] = "tekst",
["type"] = "tüüp"
},
["hi"] = {
["aside"] = "अलग",
["bgcolor"] = "bgcolor",
["bordercolor"] = "bordercolour",
["class"] = "क्लास",
["collapsed"] = "छोटा",
["comment"] = "टिप्पणी",
["dismiss"] = "हटाएँ",
["header"] = "हैडर",
["id"] = "id",
["image"] = "चित्र",
["imagelink"] = "imagelink",
["imagewidth"] = "imagewidth",
["style"] = "स्टाइल",
["text"] = "टेक्स्ट",
["type"] = "प्रकार"
},
["ja"] = {
["aside"] = "アサイド",
["bgcolor"] = "背景色",
["bordercolor"] = "境界線の色",
["class"] = "クラス",
["collapsed"] = "折り畳む",
["comment"] = "コメント",
["dismiss"] = "後で見る",
["header"] = "ヘッダー",
["id"] = "ID",
["image"] = "画像",
["imagelink"] = "画像リンク",
["imagewidth"] = "画像の幅",
["style"] = "スタイル",
["text"] = "テキスト",
["type"] = "種類"
},
["pl"] = {
["aside"] = "aside",
["bgcolor"] = "tło",
["bordercolor"] = "krawędź",
["class"] = "klasa",
["collapsed"] = "zwinięty",
["comment"] = "komentarz",
["dismiss"] = "Odrzuć",
["header"] = "nagłówek",
["id"] = "id",
["image"] = "obraz",
["imagelink"] = "link obrazu",
["imagewidth"] = "szerokość obrazu",
["style"] = "style",
["text"] = "tekst",
["type"] = "typ"
},
["pt-br"] = {
["aside"] = "de lado",
["bgcolor"] = "bgcolor",
["bordercolor"] = "cor da borda",
["class"] = "class",
["collapsed"] = "recolher",
["comment"] = "comentário",
["dismiss"] = "Dispensar",
["header"] = "cabeçalho",
["id"] = "id",
["image"] = "imagem",
["imagelink"] = "link imagem",
["imagewidth"] = "largura da imagem",
["style"] = "estilo",
["text"] = "texto",
["type"] = "tipo"
},
["ru"] = {
["aside"] = "текст справа",
["bgcolor"] = "bgcolor",
["bordercolor"] = "bordercolor",
["class"] = "class",
["collapsed"] = "collapsed",
["comment"] = "дополнение",
["dismiss"] = "dismiss",
["header"] = "заголовок",
["id"] = "id",
["image"] = "изображение",
["imagelink"] = "ссылка в изображении",
["imagewidth"] = "ширина изображения",
["style"] = "style",
["text"] = "текст",
["type"] = "type"
},
["tr"] = {
["aside"] = "kenar",
["bgcolor"] = "aprengi",
["bordercolor"] = "kenarlıkrengi",
["class"] = "sınıf",
["collapsed"] = "daratılmış",
["comment"] = "yorum",
["dismiss"] = "Kapat",
["header"] = "başlık",
["id"] = "kimlik",
["image"] = "resim",
["imagelink"] = "resimbağlantısı",
["imagewidth"] = "resimgenişliği",
["style"] = "stil",
["text"] = "metin",
["type"] = "tür"
},
["vi"] = {
["aside"] = "phía bên",
["bgcolor"] = "màu nền",
["bordercolor"] = "màu viền",
["class"] = "lớp",
["collapsed"] = "đã đóng",
["comment"] = "bình luận",
["dismiss"] = "Bỏ qua",
["header"] = "tiêu đề",
["id"] = "id",
["image"] = "hình ảnh",
["imagelink"] = "liên kết ảnh",
["imagewidth"] = "độ rộng ảnh",
["style"] = "phong cách",
["text"] = "văn bản",
["type"] = "loại"
},
["zh"] = {
["aside"] = "侧栏",
["bgcolor"] = "背景颜色",
["bordercolor"] = "边框颜色",
["class"] = "类",
["collapsed"] = "折叠",
["comment"] = "备注",
["dismiss"] = "关闭",
["header"] = "标题",
["id"] = "id",
["image"] = "图像",
["imagelink"] = "图像链接",
["imagewidth"] = "图像宽度",
["style"] = "样式",
["text"] = "文字",
["type"] = "类型"
},
["zh-tw"] = {
["aside"] = "邊界",
["bgcolor"] = "背景色彩",
["bordercolor"] = "邊框色彩",
["class"] = "屬性",
["collapsed"] = "摺疊",
["comment"] = "評論",
["dismiss"] = "忽略",
["header"] = "標頭",
["id"] = "ID",
["image"] = "圖片",
["imagelink"] = "圖片連結",
["imagewidth"] = "圖片長度",
["style"] = "樣式",
["text"] = "文字",
["type"] = "類型"
}
}
-- </nowiki>
3c5772bbe339d15222be2721369680778a157ae1
Модуль:Unsubst
828
21
28
2024-04-29T03:32:10Z
Genka Barboskin
2
Новая страница: «local checkType = require('libraryUtil').checkType local p = {} local BODY_PARAM = '$B' local specialParams = { ['$params'] = 'parameter list', ['$aliases'] = 'parameter aliases', ['$flags'] = 'flags', ['$format'] = 'date format', ['$B'] = 'template content' } function p.main(frame, body) -- If we are substing, this function returns a template invocation, and if -- not, it returns the template body. The template body can be specified in -- the bo...»
Scribunto
text/plain
local checkType = require('libraryUtil').checkType
local p = {}
local BODY_PARAM = '$B'
local specialParams = {
['$params'] = 'parameter list',
['$aliases'] = 'parameter aliases',
['$flags'] = 'flags',
['$format'] = 'date format',
['$B'] = 'template content'
}
function p.main(frame, body)
-- If we are substing, this function returns a template invocation, and if
-- not, it returns the template body. The template body can be specified in
-- the body parameter, or in the template parameter defined in the
-- BODY_PARAM variable. This function can be called from Lua or from
-- #invoke.
-- Return the template body if we aren't substing.
if not mw.isSubsting() then
if body ~= nil then
return body
elseif frame.args[BODY_PARAM] ~= nil then
return frame.args[BODY_PARAM]
else
error(string.format(
"no template content specified (use parameter '%s' from #invoke)",
BODY_PARAM
), 2)
end
end
-- Sanity check for the frame object.
if type(frame) ~= 'table'
or type(frame.getParent) ~= 'function'
or not frame:getParent()
then
error(
"argument #1 to 'main' must be a frame object with a parent " ..
"frame available",
2
)
end
-- Find the invocation name.
local mTemplateInvocation = require('Module:Template invocation')
local name = mTemplateInvocation.name(frame:getParent():getTitle())
-- Combine passed args with passed defaults
local args = {}
local format = frame.args['$format'] or 'j xg Y'
if string.find( ','..(frame.args['$flags'] or '')..',', ',%s*override%s*,' ) then
for k, v in pairs( frame:getParent().args ) do
args[k] = v
end
for k, v in pairs( frame.args ) do
if not specialParams[k] then
if v == '__DATE__' then
v = mw.getContentLanguage():formatDate( format )
end
args[k] = v
end
end
else
for k, v in pairs( frame.args ) do
if not specialParams[k] then
if v == '__DATE__' then
v = mw.getContentLanguage():formatDate( format )
end
args[k] = v
end
end
for k, v in pairs( frame:getParent().args ) do
args[k] = v
end
end
-- Trim parameters, if not specified otherwise
if not string.find( ','..(frame.args['$flags'] or '')..',', ',%s*keep%-whitespace%s*,' ) then
for k, v in pairs( args ) do args[k] = mw.ustring.match(v, '^%s*(.*)%s*$') or '' end
end
-- Pull information from parameter aliases
local aliases = {}
if frame.args['$aliases'] then
local list = mw.text.split( frame.args['$aliases'], '%s*,%s*' )
for k, v in ipairs( list ) do
local tmp = mw.text.split( v, '%s*>%s*' )
aliases[tonumber(mw.ustring.match(tmp[1], '^[1-9][0-9]*$')) or tmp[1]] = ((tonumber(mw.ustring.match(tmp[2], '^[1-9][0-9]*$'))) or tmp[2])
end
end
for k, v in pairs( aliases ) do
if args[k] and ( not args[v] or args[v] == '' ) then
args[v] = args[k]
end
args[k] = nil
end
-- Remove empty parameters, if specified
if string.find( ','..(frame.args['$flags'] or '')..',', ',%s*remove%-empty%s*,' ) then
local tmp = 0
for k, v in ipairs( args ) do
if v ~= '' or ( args[k+1] and args[k+1] ~= '' ) or ( args[k+2] and args[k+2] ~= '' ) then
tmp = k
else
break
end
end
for k, v in pairs( args ) do
if v == '' then
if not (type(k) == 'number' and k < tmp) then args[k] = nil end
end
end
end
-- Order parameters
if frame.args['$params'] then
local params, tmp = mw.text.split( frame.args['$params'], '%s*,%s*' ), {}
for k, v in ipairs(params) do
v = tonumber(mw.ustring.match(v, '^[1-9][0-9]*$')) or v
if args[v] then tmp[v], args[v] = args[v], nil end
end
for k, v in pairs(args) do tmp[k], args[k] = args[k], nil end
args = tmp
end
return mTemplateInvocation.invocation(name, args)
end
p[''] = p.main -- For backwards compatibility
return p
66516cd1b82c9c1f13ac5cc5b9a87e1c93242068